我正在尝试将 mysql 日期时间字段转换为另一个时区。当我打印日期对象时,转换似乎是正确的,但是当我将日期打印为字符串时,时间不正确。源代码和输出如下。
资源:
编辑 - 以秒和字符串打印原始间隔,添加时区
interval = [NSNumber numberWithDouble: seconds];
NSLog(@"interval in ms: %@",interval);
self.dateStamp = [[NSDate alloc] initWithTimeIntervalSince1970:seconds/1000];
if(![currentZone.name isEqualToString: timezone]){ //need to convert
NSDateFormatter *fromTZ = [[NSDateFormatter alloc]init];
[fromTZ setTimeZone:currentZone];
[fromTZ setDateFormat:@"hh:mm yyyy-MM-dd"];
NSLog(@"original date: %@",[fromTZ stringFromDate:self.dateStamp]);
NSDateFormatter *toTZ = [[NSDateFormatter alloc]init];
[toTZ setTimeZone:spotZone];
[toTZ setDateFormat:@"hh:mm yyyy-MM-dd"];
NSString *tempdate = [fromTZ stringFromDate:self.dateStamp];
NSDate *toDate = [toTZ dateFromString:tempdate];
NSLog(@"Date: %@",toDate);
NSLog(@"Date String: %@", [toTZ stringFromDate:toDate]);
}
输出:
间隔毫秒:1384193573000
original date: 01:12 2013-11-11 //当前时区日期: America/Phoenix
日期:2013-11-11 08:12:00 +0000 //新时区日期:美国/纽约
日期字符串:2013-11-11 01:12