iOS 年月日星期格式

创建一个获取日期星期格式的类

可以根据自己需求去修改,比如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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容