如何以24小时格式获取日期

时间:2016-01-16 08:28:30

标签: ios formatting nsdate nstimeinterval

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。

但是,我希望24小时格式如14:15:00。我也想要时间。我怎么能得到它。

1 个答案:

答案 0 :(得分:1)

如果您需要一个以您需要的格式表示时间的字符串,请尝试使用NSDateFormatter并将其设置为GMT timeZone并在您的情况下设置为dateFormatHH: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

相关问题