如何更改 swift 中的日期格式 2021-30-06T05:00:00+07:00?

how to change date format 2021-30-06T05:00:00+07:00 in swift?

我想将日期格式从 2021-30-06T05:00:00+07:00 更改为仅获取格式为 hh:mm:ss 的时间,但我没有得到。 这是我已经尝试过的代码

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "GMT+7")
let date = dateFormatter.dateFromString("2021-30-06T05:00:00+07:00")

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
let timeStamp = dateFormatter.stringFromDate(date!)

print(timeStamp)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale.current
print(dateFormatter.string(from: post.createdDate))

使用 DateFormatter 而不是 NSDateFormatter

您的 2021-30-06T05:00:00+07:00yyyy-MM-dd'T'HH:mm:ss 不匹配。

日期格式应为 yyyy-dd-MM'T'HH:mm:ssZZZZZ.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ssZZZZZ"
let date = dateFormatter.date(from: "2021-30-06T05:00:00+07:00")

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date!)
print(timeStamp)

输出:

03:30:00  // This is as per my current timezone.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ssZZZZZ"
let yourDate = dateFormatter.date(from: "2021-30-06T05:00:00+07:00")

// change to local time zone from your format
dateFormatter.dateFormat = "dd MMMM yyyy HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
let DateString = dateFormatter.string(from: yourDate!)
print(DateString)