快速将时间字符串转换为日期 [英] Convert time string into date swift
问题描述
我使用 firebase 作为后端并存储像这样的 7:00 PM 时间字符串.
I am using firebase as a backend and storing a string of time like this 7:00 PM.
我正在尝试将从 Firebase 收到的字符串转换为 NSDate 以便我可以对其进行排序、更改时间等
I am trying to convert the string received from Firebase and convert it into NSDate so I can sort it, change the time..etc
到目前为止,我已经在网上查找并提出了此代码
I've looked online and come up with this code so far
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.locale = NSLocale.current
dateFormatter.timeZone = NSTimeZone.local
let date = dateFormatter.date(from: item)
self.times.append(date!)
print("Start: \(date)")
其中 item 是字符串(晚上 7:00)
where item is the string (7:00 PM)
当我运行应用程序时,控制台返回:
When I run the app, the console returns:
项目:上午 9:00
Item: 9:00 AM
开始:可选(2000-01-01 05:00:00 +0000)
Start: Optional(2000-01-01 05:00:00 +0000)
我已经设置了时区、语言环境、格式.为什么返回的时间不正确?
Ive set timezone, locale, format. Why is the time being returned not correct?
打印出一些其他示例:
项目:下午 1:20
开始:可选(2000-01-01 17:20:00 +0000)
Start: Optional(2000-01-01 17:20:00 +0000)
项目:上午 9:40
开始:可选(2000-01-01 05:40:00 +0000)
Start: Optional(2000-01-01 05:40:00 +0000)
项目:上午 10:00
Item: 10:00 AM
开始:可选(2000-01-01 05:00:00 +0000)
Start: Optional(2000-01-01 05:00:00 +0000)
项目:下午 12:00
Item: 12:00 PM
开始:可选(2000-01-01 17:00:00 +0000)
Start: Optional(2000-01-01 17:00:00 +0000)
推荐答案
永远记住这一点:Date
/NSDate
以 UTC 格式存储时间.如果您的时区不是 UTC,则 print(date)
返回的值将始终不同.
Always remember this: Date
/ NSDate
stores times in UTC. If your timezone is anything but UTC, the value returned by print(date)
will always be different.
您可以通过指定 UTC 时区,使其打印出存储在 Firebase 中的小时.默认为用户(即您的)时区:
You can make it print out the hour as stored in Firebase by specifying a UTC timezone. The default is the user's (i.e. your) timezone:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let item = "7:00 PM"
let date = dateFormatter.date(from: item)
print("Start: \(date)") // Start: Optional(2000-01-01 19:00:00 +0000)
这篇关于快速将时间字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!