我想使用Swift根据系统时区将UTC日期转换为系统日期之前对我有用

问题描述

func getDateWithoutTimeFordisplay() -> String {
    let formatter = DateFormatter()
    //     formatter.locale = Locale(identifier: "en_US")
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: "UTC")
    formatter.locale = Locale(identifier: "en_US_POSIX")
    let myStringafd = formatter.date(from: self)

    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"
    dateFormatter.timeZone = NSTimeZone.local
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    if let myStringafd =  myStringafd {
        let somedateString = dateFormatter.string(from: myStringafd)
        return somedateString
    }
    return ""
}

这是我的代码,用于根据本地时区将给定的UTC日期转换为系统日期。 实际问题是,假设情况“我的日期为25-08-2020,时间为1.00 AM,根据印度时区(UTC时间比印度时间小5.30),相应的UTC日期为24-08- 2020年由于与印度时间存在时差”。在这种情况下,我想将UTC日期(因为它影响要向用户显示的日期)转换为当前系统日期。

我的系统日期和时间是25-08-2020 1:00 AM(印度时间) 对应的UTC日期为24-08-2020。 -5:30 hr

我需要将UTC日期转换为当前本地时间

解决方法

尝试一下:

let currentDate = self.UTCToLocal(date: Date().description) //This will pass system date in UTC format to the function and function will return desired output in local timezone

func UTCToLocal(date: String) -> String {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssz" //The date format should be exact as same as UTC date
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = NSTimeZone.local
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" //The desired date format in which you may want to return the value
    
    return dateFormatter.string(from: dt!)
}

或者您可以查看此帖子-Returning nil when converting string to date in swift和此日期格式链接-https://nsdateformatter.com/