如何以 24 小时格式获取日期
How can I get the date in 24 hours format
NSDate *localDate = [NSDate date];
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset];
这给了我 12 小时格式的时间。因此,例如现在是下午 2.15。它给了我 2016-01-16 02:15:00 +0000.
但是,我想要像 14:15:00 这样的 24 小时格式。我也想要时间。我怎样才能得到它。
如果您需要一个以您需要的格式表示时间的字符串,请尝试使用 NSDateFormatter 并将其设置为 GMT timeZone
和所需的 dateFormat
(在您的情况下为 HH:mm:ss
)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSLog(@"Current time in GMT = %@", [formatter stringFromDate:[NSDate date]]);
这将以 GMT 时区
格式打印时间 12:34:56
有关日期格式的详细信息,请参阅 this fine article
NSDate *localDate = [NSDate date];
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset];
这给了我 12 小时格式的时间。因此,例如现在是下午 2.15。它给了我 2016-01-16 02:15:00 +0000.
但是,我想要像 14:15:00 这样的 24 小时格式。我也想要时间。我怎样才能得到它。
如果您需要一个以您需要的格式表示时间的字符串,请尝试使用 NSDateFormatter 并将其设置为 GMT timeZone
和所需的 dateFormat
(在您的情况下为 HH:mm:ss
)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSLog(@"Current time in GMT = %@", [formatter stringFromDate:[NSDate date]]);
这将以 GMT 时区
格式打印时间12:34:56
有关日期格式的详细信息,请参阅 this fine article