首页 > 解决方案 > 获取给定时间格式的错误日期

问题描述

我有这样的时间.. 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上面给出。

标签: iosswiftnsdate

解决方案


由于使用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
}

推荐阅读