美文网首页
NSDate的一些时间日期格式

NSDate的一些时间日期格式

作者: 怒气男孩 | 来源:发表于2017-01-13 15:27 被阅读0次

    NSDate是获取当前时间信息的操作,代码如下:

    //初始化NSDate
        NSDate *date = [NSDate date];
        // 打印结果: 当前时间 date = 2017-01-13 06:50:49 +0000
        NSLog(@"当前时间 date = %@",date);
    

    可是目前具体时间是



    这中间相差了8个小时的时间,这是因为时区的问题。解决方法是在后面再添上这么一段代码:

    NSTimeZone *zone = [NSTimeZone systemTimeZone];//系统所在时区
        
        NSInteger interval = [zone secondsFromGMTForDate: date];
        
        NSDate *localDate = [date  dateByAddingTimeInterval: interval];
        
        // 打印结果 正确当前时间 localDate = 2017-01-13 14:57:04 +0000
        NSLog(@"正确当前时间 localDate = %@",localDate);
    

    这样就能拿到你所在时区的准=准确时间了。

    但如果我们不喜欢2017-01-13 14:57:04 +0000这样的格式,想把它转变成另外一种表现的格式时,就要用到NSDateFormatter语句了。****NSDateFormatter****是NSDate的格式转换语句,装换方式为(接着上面的代码):

    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.dateStyle = kCFDateFormatterShortStyle;
    fmt.timeStyle = kCFDateFormatterShortStyle;
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSString* dateString = [fmt stringFromDate:localDate];
    NSLog(@"%@", dateString);
    

    得到的结果为:1/13/17, 11:13 PM
    除此之外,还有其他的一些格式,在NSDateFormatterStyle里:

    typedef enum {
    NSDateFormatterNoStyle = kCFDateFormatterNoStyle, 
    NSDateFormatterShortStyle = kCFDateFormatterShortStyle,//“01/13/37” or “14:57pm”
    NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle,//"Nov 13, 2017" 
    NSDateFormatterLongStyle = kCFDateFormatterLongStyle,//"November 13, 2017” or “14:57:32pm" 
    NSDateFormatterFullStyle = kCFDateFormatterFullStyle//“Tuesday, April 13, 2017 AD” or “14:57:42pm PST”
    } NSDateFormatterStyle;
    

    如果我们想转换得到中文的格式,就把上面的一段代码
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];//en_US指的是英语
    把这段代码改写成:
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//zh_CN指的是中文
    于是显示的时间格式就会变成

    typedef CF_ENUM(CFIndex, CFDateFormatterStyle) {    // date and time format styles
        kCFDateFormatterNoStyle = 0,       // 无输出
        kCFDateFormatterShortStyle = 1,    // 17-01-13 下午2:57
        kCFDateFormatterMediumStyle = 2,   // 2017-01-13 下午2:57:43
        kCFDateFormatterLongStyle = 3,     // 2017年01月13日 GMT+0800下午14时57分08秒
        kCFDateFormatterFullStyle = 4      // 2017年01月13日星期五 中国标准时间下午14时57分49秒
    };
    

    我们还可以通过-setDateFormatter语句来自定义格式

    NSDate *date = [NSDate date];
    NSDateFormatter *f = [NSDateFormatter new];
    NSString *ft = @"Y-MM-dd HH:m:SS z";
    //[f setDateStyle:NSDateFormatterFullStyle];
    [f setDateFormat:ft];
    NSLog(@"%@",[f stringFromDate:date]);
    

    结果为:2017-01-13 15:33:61 GMT+8
    其它一些自定义格式的书写形式:

    自定义格式

    相关文章

      网友评论

          本文标题:NSDate的一些时间日期格式

          本文链接:https://www.haomeiwen.com/subject/inlsbttx.html