将日期转换为字符串,格式为" yyyy-MM-dd' T' HH:mm:ssZ"

时间:2018-04-12 06:43:00

标签: ios swift date

我的Swift代码:

let format = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone.current
let date = Date()
print(dateFormatter.string(from: date))

结果的格式总是如" 2018-04-12T13:33:18 + 0700" 可以设置结果格式,如" 2018-09-19T17:00:00Z"

3 个答案:

答案 0 :(得分:1)

如果您需要特定格式,则必须将时区设置为UTC

dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

并使用日期格式"yyyy-MM-dd'T'HH:mm:ssX"X代替Z

更简单的方法是ISO8601DateFormatter

let dateFormatter = ISO8601DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = Date()
print(dateFormatter.string(from: date))

答案 1 :(得分:0)

您使用的日期格式错误,Z将显示为'Z'

  

日期格式: "yyyy-MM-dd'T'HH:mm:ss'Z'"

Z表示GMT / UTC时区。

Z =祖鲁时间=> GMT + 0

<强>校正:

将日期格式更新为:

let format = "yyyy-MM-dd'T'HH:mm:ss'Z'"

答案 2 :(得分:0)

{
  "Configuration": {
    "ConnectionString": "",
    "ConnectionString2": "",
    "UnProcessedHeaderFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Header-{0:yyyyMMddHHmmss}.txt",
    "UnProcessedDetailFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Detail-{0:yyyyMMddHHmmss}.txt",
    "ApplicationTriggerFile": "\\\\edisilon01\\PROD\\Reporting\\InputFiles\\Factor\\DR\\Factor.txt",
    "DB2ConnectionString": ""
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "\\\\ECPCICS\\Files\\Generator\\log\\log-.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:dd-MMM-yyyy HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}