swift 中的日期格式化程序

Date Formatter in swift

我想获得这种类型的甲酸盐 -> 2018 年 4 月 20 日 9:02:00 下午 UTC+5:30 对于 Firestore 时间戳。我已经尝试过这段代码,但没有像上面那样得到正确的甲酸盐。

let date = Date()
let formatter = DateFormatter()

formatter.dateFormat = "MMMM d yyyy hh:mm:ss a Z"
formatter.timeZone = NSTimeZone(name: "IST") as TimeZone?

let result = formatter.string(from: date)
print(result)

已经在使用这个格式化程序 formatter.dateFormat = "MMMM d yyyy'T'hh:mm:ss a Z"

谢谢

你可以这样使用:

    let date = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss a 'UTC'Z" //If you dont want static "UTC" you can go for ZZZZ instead of 'UTC'Z.
    formatter.timeZone = TimeZone(abbreviation: "IST")
    let result1 = formatter.string(from: date)
    print(result1)

Note: If you do not want the UTC to be static in the string, you can also use the format "MMMM dd, yyyy 'at' hh:mm:ss a ZZZZ"

感谢Larme格式改进

输出:

喜欢

    let formatter = DateFormatter()
    //If you want it in your specific format you can simply add 'UTC'
    formatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss a 'UTC'Z"
    formatter.timeZone = NSTimeZone(name: "IST") as TimeZone?
    let result = formatter.string(from: Date())
    print(result)

Note: if you want to set the currentTimezone for your string then use the format "MMMM dd, yyyy 'at' hh:mm:ss a ZZZZ"

你得到的输出为

如果您不想在小时中使用前导零,请尝试此操作,因为小时只有一个数字。此外,您不需要将 NSTimeZone 强制转换为 TimeZone。可以直接使用TimeZone。

let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy 'at' h:mm:ss a 'UTC'Z"
formatter.timeZone = TimeZone(abbreviation: "IST")
let result = formatter.string(from: date)
print(result)

April 23, 2018 at 3:09:01 PM UTC+0530