美文网首页
日期(NSDate)和日期格式器(NSDateFormatter

日期(NSDate)和日期格式器(NSDateFormatter

作者: nalis风 | 来源:发表于2016-07-19 11:24 被阅读223次

    日期与时间(NSDate)

    NSDate *date1=[NSDate date];//获取代表当前日期、时间

    NSDate* date2=[[NSDate alloc]initWithTimeIntervalSinceNow:3600*24];//从当前开始一天之后

    NSDate* date3=[[NSDate alloc]initWithTimeIntervalSinceNow:-3600*24];//从当前开始一天之前

    NSDate* date4=[NSDate dateWithTimeIntervalSince1970:3600*24*366*20];//获取1970年1月1日开始,20年之后的日期

    NSLocale *cn=[NSLocale currentLocale];//获取系统当前的locale

    NSLog(@"%@",[date1 descriptionWithLocale:cn]);//获取NSDate在当前Locale下对应当的字符串

    NSDate* earlier=[date1 earlierDate:date2];//获取两个日期之间较早的日期

    NSDate* later=[date1 laterDate:date2];//较晚

    //比较两个NSDate

    switch ([date1 compare:date3]) {

    case NSOrderedAscending:

    NSLog(@"date1 位于date3之前");

    break;

    case NSOrderedSame:

    NSLog(@"date1与date3相同");

    break;

    case NSOrderedDescending:

    NSLog(@"date1 位于date3之后");

    break;

    default:

    break;

    }

    [date1 timeIntervalSinceDate:date2];//两时间的时间差

    [date2 timeIntervalSinceNow];//与现在时间的时间差

    NSLocale 代表一个语言、国际环境,比如安陆的简体中文,就可通过NSLocale对象来代表。同样一个日期,在不同的语言、国家环境下,显现出来的字符串是不同的。

    日期格式器(NSDateFormatter)

    NSDate* dt=[NSDate dateWithTimeIntervalSince1970:

    3600*24*366*20];

    NSLocale* locales[]={

    [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"],

    [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]

    };//locales数组,定义中国和美国环境

    NSDateFormatter* df[8];

    df[0]=[[NSDateFormatter alloc]init];

    //设置NSDateFormatter的日期、时间风格

    [df[0] setDateFormat:@"yyyy-MM-dd-HH-mm"];

    [df[0] setLocale:locales[0]];

    NSLog(@"%@",[df[0] stringFromDate:dt]);

    NSString* dateStr=[df[0] stringFromDate:dt];//日期转字符串

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

    [df2 setDateFormat:@"yyyy-MM-dd-HH-mm"];

    NSDate* strDate=[df2 dateFromString:dateStr];//字符串转日期

    NSLog(@"%@",strDate);

    相关文章

      网友评论

          本文标题:日期(NSDate)和日期格式器(NSDateFormatter

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