我有日期时间格式的字符串,例如:2013-05-28 10:56:31
如何将此字符串格式化为 iPhone 默认格式? (在 iPhone 设置中)
以及如何在 GMT 中设置日期时间加上时移偏移(也在 iPhone 中设置)。例如格林威治标准时间+1
这可能吗?
最佳答案
您可以使用 NSDateFormatter 来实现这一点。
NSString *dateString = @"2013-05-28 10:56:31";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//Special Locale for fixed dateStrings
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:locale];
//Assuming the dateString is in GMT+00:00
//formatter by default would be set to local timezone
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date =[formatter dateFromString:dateString];
//After forming the date set local time zone to formatter
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:localTimeZone];
NSString *newTimeZoneDateString = [formatter stringFromDate:date];
NSLog(@"%@",newTimeZoneDateString);
有关使用 dateFormatter 的一些提示。
- 如果字符串不包含任何有关时区的信息,并且它与设备中的时区不同,请始终将时区设置为 dateFormatter。
- 对于固定格式的日期字符串,始终使用
en_US_POSIX
locale - 登录控制台时的 NSDate 总是显示在 GMT+00:00。 NSDate 没有时区,它只是在不同的时区表示时不同。
- 通过将新时区设置为格式化程序,将形成的日期转换为任何时区。 Formatter 从不更改日期,它只是重新计算它在这个新时区中的表示方式。
关于ios - 来自 iPhone 设置和 GMT 偏移的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16790832/