(一)时区问题
NSDate *date1 = [NSDatedate]; //格林时间
NSLog(@"date1第一次 %@",date1);
NSTimeZone *timeZone = [NSTimeZonesystemTimeZone];
NSInteger seconds = [timeZonesecondsFromGMTForDate:date1];
date1 = [date1dateByAddingTimeInterval:seconds]; //转为当前时区的时间
NSLog(@"date1第二次 %@",date1);
输入结果:
2013-11-08 15:57:49.017 NSDate[2093:a0b] date1第一次 2013-11-08 07:57:49 +0000
2013-11-08 15:57:49.017 NSDate[2093:a0b] date1第二次 2013-11-08 15:57:49 +0000
总结:用[NSDate date]得到的时间是格林时间,同我们的真正时间正好相差8个小时,要将当前时间根据格林时区同本地时区计算一个时间差,当前时间再加上时间差,即可得到当前时区下正确时间
(二)字符转日期
NSString *dateStr = @"2013-11-08";
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formattersetDateFormat:@"yyyy-MM-dd"];
//设置了时区,但是没有起到作用
[formatter setTimeZone:[NSTimeZonesystemTimeZone]];
// 由字符转为日期,得到的日期是格林时间的日期
NSDate *date2 = [formatter dateFromString:dateStr];
NSLog(@"date2____1= %@",date2);
NSTimeZone *timeZone = [NSTimeZonesystemTimeZone];
NSInteger seconds = [timeZone secondsFromGMTForDate:date2];
date2 = [date2dateByAddingTimeInterval:seconds];
NSLog(@"date2____2 = %@",date2);
输出结果:
2013-11-08 16:08:26.063 NSDate[2195:a0b] date2____1= 2013-11-07 16:00:00 +0000
2013-11-08 16:08:26.063 NSDate[2195:a0b] date2____2 = 2013-11-08 00:00:00 +0000
总结:把字符转为日期,得到的日期是格林时区 时间
(三)日期转字符
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[formatter setTimeZone:[NSTimeZonesystemTimeZone]];
NSDate *date = [NSDatedate];
NSLog(@"date = %@",date); //格林时间
NSString *dateStr = [formatter stringFromDate:date];
NSLog(@"dateStr = %@",dateStr);//得到字符串是当前时区下正确时间
结果:
2013-11-08 16:19:32.042 NSDate[2241:a0b] date = 2013-11-08 08:19:32 +0000
2013-11-08 16:19:32.042 NSDate[2241:a0b] dateStr = 2013-11-08 04:19:32
总结:当前时间转为字符串后,是当时时区下正确时间
日期转星期
- (NSString *)weekDayFromDate:(NSDate *)now{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
now=[NSDate date];
comps = [calendar components:unitFlags fromDate:now];
NSInteger week = [comps weekday];
NSString *weekStr = nil;
switch (week) {
case 1:{
weekStr = @"周日";
break;
}
case 2:{
weekStr = @"周一";
break;
}
case 3:{
weekStr = @"周二";
break;
}
case 4:{
weekStr = @"周三";
break;
}
case 5:{
weekStr = @"周四";
break;
}
case 6:{
weekStr = @"周五";
break;
}case 7:{
weekStr = @"周六";
break;
}
default:
break;
}
NSLog(@"weekStr = %@",weekStr);
return nil;
}