IOS--获取当前时间和当前时间戳及NSLocale的重要性

//获取当前的时间,格式YYYY-MM-dd HH:mm:ss
+(NSString*)getCurrentTimes{
    //获取当前时间
    NSDate *datenow = [NSDate date];
    
    //创建时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    /**
     **设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
     **使用时间戳的目的,是为了自定义时间的打印格式
     **/
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    /**
     **设置本地化区域信息-----尤其多国语言时需要注意
     **不同地区有不同的日期格式。使用这个方法的目的:得到指定地区指定日期字段的一个合适的格式
     **(通常你可以通过currentLocal查看当前所属地区)
     **/
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    
    //将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

NSDateFormatter对象中locale属性代表“本地化信息”。
下面这个例子给我们表现了英式英语、美式英语、中国不同的日期格式:

//获取当前的时间,格式YYYY-MM-dd HH:mm:ss
-(void)getCurrentTimes{
    
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    NSLocale *cnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];

    NSString *dateFormat;
    NSString *dateComponents = @"YYYY-MM-dd HH:mm:ss";
    
    dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
    NSLog(@"Date format for %@: %@",[usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);
    
    dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
    NSLog(@"Date format for %@: %@",[gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);
    
    dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:cnLocale];
    NSLog(@"Date format for %@: %@",[cnLocale displayNameForKey:NSLocaleIdentifier value:[cnLocale localeIdentifier]], dateFormat);
    // Output:
    // Date format for English (United States) : MM/dd/YYYY, HH:mm:ss
    // Date format for English (United Kingdom): dd/MM/YYYY, HH:mm:ss
    // Date format for 中文     (中国)           : YYYY/MM/dd HH:mm:ss
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值