将字符串转换为日期到时间字符串



我从API收到一个String,这是对象创建时间。格式是特定的,所以我无法确定如何转换它。

2021-07-07T15:03:21.409Z

我试着把它转换成这样的日期:

extension String {
func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss") -> 
Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")
dateFormatter.locale = Locale(identifier: "fr-FR")
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
}

但它正在返回nil。我想withFormat部分在我的toDate()函数中不好,但我不确定

然后我想再次将其转换为以前的字符串,如下所示(在SO上找到(:

extension Date {
func timeAgoDisplay() -> String {
let calendar = Calendar.current
let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!
if minuteAgo < self {
let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
return "(diff) sec ago"
} else if hourAgo < self {
let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
return "(diff) min ago"
} else if dayAgo < self {
let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
return "(diff) hrs ago"
} else if weekAgo < self {
let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
return "(diff) days ago"
}
let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
return "(diff) weeks ago"
}
}

这其实很简单。。。答案是简单地使用这样的格式化程序:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd H:mm:ss.SSSS"
let currentTime = df.string(from: Date())
//currentTime is your string. You can change date formatter as you wish!

在本例中,DateFormatter((将日期格式化为特定格式,然后进行转换!

不同部分的意思是:yyyy是四位数的年份,MM是类似08或12之类的月份,dd是两位数的日期,H是军事时间0-24,hh是0-12之间的小时,mm是分钟,ss.SSSS是秒,小数点后四位的秒。

如果你想要这些信件,你可以这样做:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'H:mm:ss.SSSS'Z'"
let currentTime = df.string(from: Date())

相关内容

  • 没有找到相关文章

最新更新