use*_*063 4 timezone date ios swift
首先,我的日期采用字符串格式:“06-04-2017 06:28:17 PM”
然后我使用以下方法转换为 Date():
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)
Run Code Online (Sandbox Code Playgroud)
这是上面的输出日期:
startdate = 2017-04-06 18:28:17 +0000
但是当我尝试使用以下代码将分钟设置为值 0 时。我的日子改变了。
let calender = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let date = calender.date(bySettingHour: Int(hour)!, minute: 00, second: 00, of: startdate!)
print(date)
Run Code Online (Sandbox Code Playgroud)
输出:2017-04-07 12:15:00 +0000
在我设置时区后,我的时区是+5:45。我遇到了同样的错误。
任何帮助。高度赞赏。
使用以下代码我得到相同的日期:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)
Run Code Online (Sandbox Code Playgroud)
**但是我这里不能将分钟设置为0。**
雨燕5
该解决方案只是将分钟和秒归零,而不会弄乱小时。
extension Date {
func startOfHour() -> Date?
{
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
components.minute = 0
components.second = 0
return calendar.date(from: components)
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
Date().startOfHour
Run Code Online (Sandbox Code Playgroud)
打印出:
日期:2019-09-05 15:09:57 +0000
开始日期:可选(2019-09-05 15:00:00 +0000)
| 归档时间: |
|
| 查看次数: |
9251 次 |
| 最近记录: |