1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
// // main.m // Date的用法 // // Created by greezen on 14-3-9. // Copyright (c) 2014年 greezen. All rights reserved. // #import <Foundation/Foundation.h> void date1(){ NSTimeZone *tz = [NSTimeZone systemTimeZone]; NSDate *date = [NSDate date];//格林威治时间 NSInteger integer = [tz secondsFromGMTForDate:date];//获取格林威治时间和本地时间相差的秒数 date = [NSDate dateWithTimeIntervalSinceNow:integer];//本地时间 //从1970-01-01 00:00:00 开始10秒后的时间 date = [NSDate dateWithTimeIntervalSince1970:10]; date = [NSDate distantFuture];//将来的某一个时间 date = [NSDate distantPast];//过去的某一个时间 NSLog(@"%@", date); //返回从1970-1-1开始走过的毫秒数 NSTimeInterval itv = [date timeIntervalSince1970]; NSLog(@"%.0f", itv); } #pragma mark 日期的比较 void dateCompare(){ NSDate *date = [NSDate date]; NSDate *date1 = [NSDate date]; NSDate *cdate = [date earlierDate:date1];//两个时间中比较早的一个时间 cdate = [date laterDate:date1];//两个时间中比较晚的一个时间 NSComparisonResult res = [date compare:date1]; if (res == NSOrderedSame) { NSLog(@"两个时间一样"); }else if (res == NSOrderedAscending){ NSLog(@"第一个时间早于第二个时间"); }else if (res == NSOrderedDescending){ NSLog(@"第一个时间晚于第二个时间"); } NSLog(@"date=%@,date1=%@,earlierDate=%@", date, date1, cdate); } #pragma mark 日期的格式化 void dateFormate(){ //法一 NSDate *date = [NSDate date]; date = [date dateWithCalendarFormat:nil timeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]]; //法二 NSDate *date1 = [NSDate date]; NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease]; formater.dateFormat = @"yyyy年MM月dd日 HH时mm分ss秒"; //formater.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; NSString *datestring = [formater stringFromDate:date1]; NSLog(@"%@", datestring); } #pragma mark 取出日期的一部分(年 月 日 时 分 秒) void calendar(){ NSCalendar *cal = [NSCalendar currentCalendar]; NSInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDateComponents *com = [cal components:flags fromDate:[NSDate date]]; NSLog(@"%li", [com minute]); } int main(int argc, const char * argv[]) { @autoreleasepool { //date1(); //dateCompare(); //dateFormate(); calendar(); } return 0; } |