在 Swift 5 中,从日期时间字符串到当前时间的时差(以天为单位)



我有一个日期时间字符串为"15/06/2019 02:03:20 PM IST"。我需要计算日期时间字符串和当前日期和时间之间的时差(以天为单位(。

我能够使用

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a zzz"
let now = Date()
print(dateFormatter.string(from: now))      //It gives output as 06/10/2019 11:08:52 AM GMT+5:30 not as IST timezone. 

但是我无法将给定的日期时间字符串转换为日期对象以获取差异。

let registrationTime = "15/06/2019 02:03:20 PM IST"
print(dateFormatter.date(from: registrationTime))       //prints nil

我尝试将日历、区域设置和时区添加到日期格式化程序,但它没有返回日期对象。我还尝试在组件中破坏注册表时间(用空格分隔(并将它们从字符串单独转换为日期,但这也不起作用。

要使其适用于印度标准时间,您需要将区域设置设置为印度的区域设置

dateFormatter.locale = Locale(identifier: "en_IN")

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a zzz"
dateFormatter.locale = Locale(identifier: "en_IN")
let now = Date()
print(dateFormatter.string(from: now))
let registrationTime = "15/06/2019 02:03:20 PM IST"
print(dateFormatter.date(from: registrationTime))

06/10/2019 09:35:48 AM GMT+2
可选(2019-06-15 08:33:20 +0000(

最新更新