NSDate 整理筆記

jopen 10年前發布 | 37K 次閱讀 NSDate Objective-C開發

1 當前時間 

        NSDate *nowDate = [NSDate date]; 

        NSLog(@"nowDate = %@",nowDate); 

2、從現在開始的24小時 

        NSTimeInterval secondsPerDay = 24*60*60; 

        NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay]; 

        NSLog(@"tomorrow = %@",tomorrow); 

3、根據已有日期創建日期 

         NSTimeInterval secondsPerDay1 = 24*60*60; 

        NSDate *now = [NSDate date]; 

        NSDate *yesterDay = [now addTimeInterval:-secondsPerDay1]; 

        NSLog(@"yesterDay = %@",yesterDay); 

4、比較日期 

        BOOL sameDate = [now isEqualToDate:yesterDay]; 

        NSLog(@"sameDate = %lu",sameDate); 

4.1、獲取較早的日期 

        NSDate *earlierDate = [yesterDay earlierDate:now]; 

        NSLog(@"earlierDate  = %@",earlierDate); 

4.2、較晚的日期 

        NSDate *laterDate = [yesterDay laterDate:now]; 

        NSLog(@"laterDate  = %@",laterDate); 

 

4.3、兩個日期之間相隔多少秒 

        NSTimeInterval secondsBetweenDates= [yesterDay timeIntervalSinceDate:now]; 

        NSLog(@"secondsBetweenDates=  %lf",secondsBetweenDates); 

4.4、通過NSCALENDAR類來創建日期 

        NSDateComponents *comp = [[NSDateComponents alloc]init]; 

        [comp setMonth:06]; 

        [comp setDay:01]; 

        [comp setYear:2001]; 

        NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

        NSDate *myDate1 = [myCal dateFromComponents:comp]; 

        NSLog(@"myDate1 = %@",myDate1); 

 

4.5、從已有日期獲取日期 

        unsigned units  = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit; 

        NSDateComponents *comp1 = [myCal components:units fromDate:now]; 

        NSInteger month = [comp1 month]; 

        NSInteger year = [comp1 year]; 

        NSInteger day = [comp1 day]; 

4.6NSDateFormatter實現日期的輸出 

        NSDateFormatter *formatter = [[NSDateFormatteralloc]init]; 

        [formatter setDateStyle:NSDateFormatterFullStyle];//直接輸出的話是機器碼 

4.7、或者是手動設置樣式[formatter setDateFormat:@"yyyy-mm-dd"]; 

        NSString *string = [formatter stringFromDate:now]; 
        NSLog(@"string = %@",string); 
        NSLog(@"formater = %@",formatter); 

4.8、獲取日期格式對象

        - (NSDateFormatter *)dateFormatter { 

if (dateFormatter == nil) { 

dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 

[dateFormatter setTimeStyle:NSDateFormatterNoStyle]; 

return dateFormatter; 

}


參考:http://www.cocoachina.com/bbs/read.php?tid=140980&keyword=NSDate

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!