日期类的常用方法

来源:互联网 发布:网络有时候不稳定会断 编辑:程序博客网 时间:2024/06/03 17:06

时间戳的概念:某一日期到1991年的秒数的大小,称改日期为时间戳。


NSData的基本概念:在FounDation框架中,提供了NSData类,它是cocoa提供给处理日期的类,它提供日期的创建,比较,计算时间间隔等功能,是最常用的类库之一。


NSDate的使用:

    //在当前日期的基础上累加一个数值,单位是秒

   //明天

    NSDate *date3 = [NSDatedateWithTimeIntervalSinceNow:24*60*60];

   NSLog(@"date3:%@",date3);

    

   //昨天

    NSDate *date4 = [NSDatedateWithTimeIntervalSinceNow:-24*60*60];

   NSLog(@"date4:%@",date4);


    //1970年上加一个数值,该数值是一个时间戳数值

    NSDate *date1970 = [NSDatedateWithTimeIntervalSince1970:0];

   NSLog(@"date1970:%@",date1970);


    //2.获取日期的时间戳

   NSTimeInterval time1970 = [date1 timeIntervalSince1970];

   NSLog(@"time1970:%f",time1970);

    

    //取得日期对象date3到当前日期时间的数值差

   NSTimeInterval timeNow = [date3 timeIntervalSinceNow];

   NSLog(@"timeNow:%f",timeNow);

    

    

    //3.日期的比较

    //(1)通过日期对象的compare方法进行比较

   NSComparisonResult result = [date3 compare:date1];

   if (result == NSOrderedDescending) {

        NSLog(@"date3 > date1");

    }

    //(2)通过比较时间戳

    if ([date3timeIntervalSince1970] > [date1 timeIntervalSince1970]) {

        NSLog(@"date3 > date1");

    } 


/*__________________________NSDateFormatter格式化日期_____________________________*/

    

    //1.日期对象格式化为字符串: 2013-07-29 15:20:59  20130729

    // 日期对象 -->  字符串

   NSDate *nowDate = [NSDatedate];

    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];

    //设置日期的格式

    [dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss"];

    //设置时区

   NSTimeZone *timezone = [NSTimeZonetimeZoneWithName:@"America/New_York"];

    [dateFormattersetTimeZone:timezone];

    

    //stringFromDate将日期对象格式化为字符串

   NSString *datestring = [dateFormatter stringFromDate:nowDate];

   NSLog(@"格式化之后:%@",datestring);

    

    //2.将字符串格式化成日期对象

    //字符串 ——>日期对象

  

    NSString *string =@"20130729 16:56:05";

   NSDateFormatter *dateFormatter2 = [[NSDateFormatteralloc] init];

    [dateFormatter2setDateFormat:@"yyyyMMdd HH:mm:ss"];

    //dateFromString: 将字符串格式化成日期对象

   NSDate *formatDate = [dateFormatter2 dateFromString:string];

   NSLog(@"%@",formatDate);

    

    

    //获取到所有时区的名称

   NSArray *zoneNames = [NSTimeZoneknownTimeZoneNames];

   for (NSString *namein zoneNames) {

       NSLog(@"%@",name);

    }


 
0 0