創(chuàng)建一個獲取日期星期格式的類
可以根據(jù)自己需求去修改票唆,比如2021-01-14
.h
typedef NS_ENUM(NSUInteger, GetChDateType) {
GetChDateTypeYMD = 0,
GetChDateTypeMD = 1,
GetChDateTypeMDWeek = 2,
GetChDateTypeYMDWeek = 3,
};
@interface GetCHdate : NSObject
+ (NSString *)getDateForType:(GetChDateType)dateType;
@end
.m
+ (NSString *)getDateForType:(GetChDateType)dateType {
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
comps = [calendar components:unitFlags fromDate:date];
NSInteger year = [comps year];
NSInteger week = [comps weekday];
NSInteger month = [comps month];
NSInteger day = [comps day];
NSString *weekStr;
switch (week) {
case 1:
weekStr = @"日";
break;
case 2:
weekStr = @"一";
break;
case 3:
weekStr = @"二";
break;
case 4:
weekStr = @"三";
break;
case 5:
weekStr = @"四";
break;
case 6:
weekStr = @"五";
break;
default:
weekStr = @"六";
break;
}
NSString *chStr;
switch (dateType) {
case GetChDateTypeYMD:
chStr = [NSString stringWithFormat:@"%.ld年%.2ld月%.2ld日",(long)year,(long)month,(long)day];
break;
case GetChDateTypeMD:
chStr = [NSString stringWithFormat:@"%.2ld月%.2ld日",(long)month,(long)day];
break;
case GetChDateTypeMDWeek:
chStr = [NSString stringWithFormat:@"%.2ld月%.2ld日 星期%@",(long)month,(long)day,weekStr];
break;
default:
chStr = [NSString stringWithFormat:@"%.ld年%.2ld月%.2ld日 星期%@", (long)year,(long)month,(long)day,weekStr];
break;
}
return chStr;
}