Foundation框架—日期类(NSDate)

Posted on 2016-01-11 13:14  WYB.iOS  阅读(192)  评论(0编辑  收藏  举报

时间类NSDate

1.创建一个日期对象

    NSDate *date1 = [[NSDate alloc] init]; //创建了一个当前的时间点
    NSDate *date2 = [NSDate date];
    NSLog(@"date2:%@",date2);
    
    2.在当前时间点的基础上,进行时间的累加

    //明天
    NSDate *date3 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];
    //昨天
    NSDate *date4 = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];
    NSLog(@"date4:%@",date4);
    
    
    3.在1970时间点的基础上,进行时间的累加

    NSDate *date1970 = [NSDate dateWithTimeIntervalSince1970:0];
    NSLog(@"date1970:%@",date1970);
    
    NSDate *date5 = [NSDate dateWithTimeIntervalSince1970:1234578];
    NSLog(@"date5:%@",date5);
    
    4.当前日期的时间戳

    //时间戳:某一日期到1970年的秒数多少,称为该日期的时间戳
    NSTimeInterval nowTime1970 = [date1 timeIntervalSince1970];
    NSLog(@"nowTime1970:%f",nowTime1970);
    
    NSTimeInterval nowTime = [date1970 timeIntervalSinceNow];
    NSLog(@"nowTime:%f",nowTime);
    
    5.日期比较

    //(1)通过时间戳比较
    //date3  明天  date4 昨天
    NSTimeInterval subTime1 = [date3 timeIntervalSince1970];
    NSTimeInterval subTime2 = [date4 timeIntervalSince1970];
    if (subTime1 < subTime2) {
        NSLog(@"date4>date3");
    }else {
        NSLog(@"date4<date3");
    }
    
    //(2)compare
    NSComparisonResult result = [date3 compare:date4];
    if (result == NSOrderedAscending) {
        NSLog(@"date3<date4");
    }else {
        NSLog(@"date3>date4");
    }

  日期格式化

1.date->string

    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:2*24*60*60];
    //2015-11-26 11:54:02 +0000   ->11月26号 11:54
    NSLog(@"date:%@",date);
    
    //2015年11月26号 11:54   yyyy年MM月dd号 HH:mm:ss
    //创建日期格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置日期化格式  E:对应星期
    [dateFormatter setDateFormat:@"yyyy年MM月dd号 HH:mm:ss E z"];

    NSString *str = [dateFormatter stringFromDate:date];
    NSLog(@"str:%@",str);


    2.设置时区

    //获取所有时区
//    NSLog(@"%@",[NSTimeZone knownTimeZoneNames]);
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Indian/Chagos"];
    [dateFormatter setTimeZone:timeZone];
    str = [dateFormatter stringFromDate:date];
    NSLog(@"str:%@",str);
    
    
    3.string->date

    //yyyy年M月dd号 HH-mm-ss
    NSString *dateString = @"2015年2月14号 13-23-56";
   
    //创建日期格式化对象
    NSDateFormatter *dateFormetter1 = [[NSDateFormatter alloc] init];
    [dateFormetter1 setDateFormat:@"yyyy年M月dd号 HH-mm-ss"];
    
    NSDate *dateStr = [dateFormetter1 dateFromString:dateString];
    NSLog(@"dateStr:%@",dateStr);

 

Copyright © 2024 WYB.iOS
Powered by .NET 8.0 on Kubernetes