object-c基础语法NSDate, 主要学习NSDate的设置、获取当前时间、当前时间加减秒后的时间、日期比较、日期转换成NSString等
1. NSDate *date =[NSDate date]; //获取当前时间
2. +(id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs; //返回以当前时间为基准,然后过了secs秒的时间
例 : NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow: 24 *60 *60]; //以当前时间为基准,过了一天。
3. +(instancetype)dateWithTimeIntervalSince1970:(NSTimeInterval)secs; //返回以1970年时间为基准,然后过了secs秒的时间
4. dateByAddingTimeInterval: //获取给定时间过了多少秒后的时间,秒数可以为负值
例 : NSDate *anHourAfter = [now dateByAddingTimeInterval:60 * 60]; //获取一小时之后的日期和时间
5. NSTimeInterval time = [[NSDatedate] timeIntervalSince1970];//获取当前时间(秒数) NSLog(@"%f",time);
timeIntervalSince1970 //表示从1970年到给定时间的秒数
6. NSTimeIntervaltime1 = [date timeIntervalSinceNow]; //返回给定时间与当前时间的时间差(秒数)
7. NSTimeIntervaltimeBetween = [date1 timeIntervalSinceDate:date2]; //获取两个日期的间隔时间差
8.
NSDate *laterOne = [date1laterDate:date2]; //获取两个时间对象中较晚的一个
9. NSDate *laterOne = [date1earlierDate:date2]; //获取两个日期时间对象中较早的一个
10. NSDateFormatter *dateFormatter = [NSDateFormatternew]; //日期时间格式化对象
例 : [dateFormattersetDateFormat:@"yyyy年MM月dd日HH时mm分ss秒a"];//2015年06月05日 13时30分10秒 下午
[dateFormattersetDateFormat:@"yyyy-MM-dd hh:mm:ss a"]; //2015-06-05 01:30:10 下午
NSString *localDateTime =[dateFormatterstringFromDate:date]; //格式化日期时间对象(把日期对象转换成字符串)
11. //把日期格式的字符串转换成日期对象
NSString *myDateTimeStr = @"2013-04-25 11:35:20";
NSDateFormatter *formatter = [NSDateFormatternew];
[formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *newDate = [formatterdateFromString:myDateTimeStr];
12. 时区://系统时区
NSTimeZone *zone = [NSTimeZonesystemTimeZone];
13. //系统时区缩写
NSString *abbStr = [zoneabbreviation];
NSLog(@"系统时区缩写:%@",abbStr);
14. //当地时区
NSTimeZone *localTimeZone = [NSTimeZonelocalTimeZone]; NSLog(@"localTimeZone:%@",localTimeZone);
15. //和格林尼治时间差
NSIntegertimeOff = [zone secondsFromGMT];
16. //时差转化
NSDate *timeOffDate = [datedateByAddingTimeInterval:timeOff];
17. 字符串转换为时间出现的时差问题解决
a. 设置时区:[formattersetTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
b. [formattersetTimeZone:[NSTimeZonetimeZoneForSecondsFromGMT:0]];
c. 时差转化(见16)