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

标签 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。我也想要时间。我怎样才能得到它。

最佳答案

如果您需要一个以您需要的格式表示时间的字符串,请尝试使用 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

关于ios - 如何以 24 小时格式获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34825017/

相关文章:

c++ - C++ cout将 double 对齐为精度为2的 double

excel - 将文本 "YYYY-MM"格式化为日期,以便您可以排序

ios - 如何在 iOS 的 tapku 库日历中禁用(用户交互关闭)过去的日期

ios - 为 HKCategoryTypeIdentifierSleepAnalysis 查询 HealthKit

ios - 在 UICollectionView 中注册多个单元格(swift 3)

iOS 应用程序在安装远程/diawi 时崩溃,但如果从 xcode 安装则不会崩溃

ios - 从 xib View 到 ViewController 的动画转场

javascript - JSON 字符串中的数学方程式

iphone - 从多个变量类型中创建一个对象

ios - 使用 dateFormat Swift 将日期转换为日期