ios - 获取给定时间格式的错误日期
问题描述
我有这样的时间..
var utcTime = "\(dic["Due_Date"]!)"
这里utcTime
显示"2020-08-23T18:49:15"
我把它分成不同的组件,像这样..
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
self.dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month, from: date) //Displays 8
let dayInt = Calendar.current.component(.day, from: date) //Displays 24 instead of 23
let yearInt = Calendar.current.component(.year, from: date) //Displays 2020
}
在这里,除了白天,我将所有组件都准备好。utcTime
显示时,显示 24而"2020-08-23T18:49:15"
不是显示 23 的日期。日期由dayInt
上面给出。
解决方案
由于使用Calendar.current
在不同时区获取日期的日期组件,您将获得不同的日期。如果要获取特定时区的日期组件,请创建日历实例并指定时区。
if let date = dateFormatter.date(from:utcTime) {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let monthInt = calendar.component(.month, from: date) //Displays 8
let dayInt = calendar.component(.day, from: date) //Displays 23
let yearInt = calendar.component(.year, from: date) //Displays 2020
}
推荐阅读
- java - 将加密逻辑从 JAVA 转换为 DART
- pandas - 如何遍历熊猫中的选定行
- rest - 由 Heroku 托管后未设置相同的站点 Cookie 属性
- php - 如何在 php 中将 DD/MM/YYYY h:i 转换为 YYYY-MM-DD h:i
- excel - Excel 不同值列表
- python-3.x - 如何从没有唯一类标识符的情况下刮取一些文本?
- bash - 全部剪到最后
- python-3.x - 将 SAS 代码转换为 KL 散度图的 Python
- reactjs - Laravel 安装:我应该为所有 bootstrap、vue 和 react 运行 php artisan ui 还是只为其中一个运行
- cocos2d-iphone - Cocos2d 无法切换场景