Objective C - 将时间从 12 格式转换为 24 格式问题
Objective C - Converting time from 12 to 24 format issue
我正在使用以下代码将时间从 12 格式转换为 24 格式,它工作正常,但结果比实际时间少了 3 小时!
即:如果时间是“12:40 pm”,我在转换为 24 格式后得到“09:40”。
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:strDate4Convert];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
提前致谢;
尝试将时区设置为 UTC
或您的 localTimeZone
而不是 systemTimeZone
。
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//Or [df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"12/02/2016 12:40 pm"];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
是的,使用本地时区
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"08/30/2016 12:40 am"]; // @"08/30/2016 12:40 pm"
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
输出:
newTimeStr的打印说明:
2016 年 8 月 30 日 00:40:00
newTimeStr的打印说明:
2016 年 8 月 30 日 12:40:00
我正在使用以下代码将时间从 12 格式转换为 24 格式,它工作正常,但结果比实际时间少了 3 小时! 即:如果时间是“12:40 pm”,我在转换为 24 格式后得到“09:40”。
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:strDate4Convert];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
提前致谢;
尝试将时区设置为 UTC
或您的 localTimeZone
而不是 systemTimeZone
。
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//Or [df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"12/02/2016 12:40 pm"];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
是的,使用本地时区
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"08/30/2016 12:40 am"]; // @"08/30/2016 12:40 pm"
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
输出:
newTimeStr的打印说明: 2016 年 8 月 30 日 00:40:00
newTimeStr的打印说明: 2016 年 8 月 30 日 12:40:00