iOS基础:NSDate

来源:互联网 发布:三星note8画画软件 编辑:程序博客网 时间:2024/06/09 20:57

一、时间创建

//1获取当前时间,为格林尼治时间

        NSDate* date1 = [NSDate date];

//2获取距离当前时间...秒的时间

        NSDate* date2 = [NSDate dateWithTimeIntervalSinceNow:3600*24];

//3获取距离1970.1.1...秒的时间

        NSDate* date3 = [NSDate dateWithTimeIntervalSince1970:0];

//4获取较早的时间

        NSDate* earlier = [date1 earlierDate:date3];

//5获取较晚的时间

        NSDate* later = [date1 laterDate:date3];

//6比较两个时间

        NSComparisonResult result = [date1 compare:date2];

//7获取与现在时间差

        NSTimeInterval cha = [date1 timeIntervalSinceNow];

//8获取两个时间的时间差

        NSTimeInterval cha1 = [date1 timeIntervalSinceDate:date2];


二、NSDateFormatter

NSDateFormatter * df = [[NSDateFormatteralloc]init];

        [dfsetDateStyle:NSDateFormatterShortStyle];

[df setTimeStyle:NSDateFormatterShortStyle];

NSLocale * cn1 = [[NSLocale allocinitWithLocaleIdentifier:@"zh_CN"];

        [dfsetLocale:cn];

//以上四项为设置具体的格式。日期格式、时间格式、时区

//如果在df里只设置了日期格式,而没有设置时间格式,按df打印时是不显示时间的。


//        将时间对象转为字符串对象输出

       NSDate * date1 = [NSDatedateWithTimeIntervalSince1970:0];

       NSDateFormatter * df1 = [[NSDateFormatteralloc]init];

      df1.dateFormat =@"yyyy-mm-dd";

       NSString * str = [df1  stringFromDate:date1];

        

//        将字符串对象转为时间对象输出

       NSString * dateStr =@"2013-11-05";

       NSDateFormatter * df2 = [[NSDateFormatteralloc]init];

      df2.dateFormat =@"yyyy-mm-dd";

       NSDate * date2 = [df2  dateFromString:dateStr];

        


0 0
原创粉丝点击