NSDate,NSDateFormatter,NSLocale

来源:互联网 发布:冷藏车配货软件 编辑:程序博客网 时间:2024/06/04 19:59
1.static NSString* const KDateFormat=@"MM-dd-yyyy";

   NSString* dateStr=@"8-1-2000";

   NSDateFormatter* dateFormat=[[NSDateFormatter alloc] init];  

   dateFormat.dateFormat=KDateFormat;

    NSDate* date=[dateFormat dateFromString:dateStr];
    NSTimeInterval interval=[date timeIntervalSince1970]//timeIntervalSince1970返回的是单位是秒

    static NSString* const KTimeFormat=@"HH:mm:ss"; 小时成大写HH是24小时制,小写hh是12小时制。


2. NSLocale 本地化

    NSLog(@"NSLocaleCountryCode:%@",[[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]);//US,ZH
    NSLog(@"NSLocaleLanguageCode:%@",[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]);//en,cn

   结果不受国际化中的语言设置而改变。它受通用/多语言环境/区域格式中的设置影响。它的意思可能是NSLocaleCountryCode国家,使用NSLocaleLanguageCode语言。


   取国际化中的语言设置

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
    NSString *currentLanguage = [languages objectAtIndex:0];
    NSLog(@"currentLanguage:%@",currentLanguage);//es,en,zh-Hans


3.时间范围
        iPickerView = [[UIDatePicker alloc] initWithFrame:CGRectZero];
        iPickerView.datePickerMode=UIDatePickerModeDate;
        double timeInterval=-60*60*24*365*50;
        NSDate* minimumDate=[NSDate dateWithTimeIntervalSinceNow:timeInterval];
        minimumDate=[NSDate dateWithTimeInterval:timeInterval sinceDate:minimumDate];//多次使用dateWithTimeInterval
        iPickerView.minimumDate=minimumDate;//100年前
        iPickerView.maximumDate=[NSDate dateWithTimeIntervalSinceNow:0];//现在


4.格式化日期
    《iPhone开发秘籍(第2版)》11.25格式化日期,表11-1 NSDateFormatter类的默认格式代码。


浮点数格式化四舍五入问题

id str=[NSString stringWithFormat:@"%.2f",1.999];  结果str为2.00

使用NSNumberFormatter可设置更多如何对数字格式化。

原创粉丝点击