【问题标题】:I want to convert UTC date to system date based on the system time zone using Swift. It worked for me earlier我想使用 Swift 根据系统时区将 UTC 日期转换为系统日期。它早些时候对我有用
【发布时间】:2020-08-25 06:25:26
【问题描述】:
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 日期转换为系统日期的代码。 实际问题是,假设“我的时间是 2020 年 8 月 25 日上午 1 点,根据印度时区,(UTC 时间比印度时间小 5.30),相应的 UTC 日期是 24-08- 2020年由于与印度时间的时差”。在这种情况下,我想将 UTC 日期(因为它影响要为用户显示的日期)转换为当前系统日期。

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

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

【问题讨论】:

  • 设置dateFormat前需要先设置locale

标签: ios swift utc


【解决方案1】:

试试这个:

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 和 dateFormatters 的链接 - https://nsdateformatter.com/

【讨论】:

  • 我想将 UTC 格式的日期转换为系统日期。我在 myStringafd 变量中有 UTC 日期。我想将其转换为本地
  • @MohammedRamshad.k 如果您打印 Date() 那么它将显示 UTC 日期类似于 2020-08-25 07:17:00 +0000 并且为了清楚地理解您可以访问此链接 - ios-tutorial.com/working-dates-swift。这个功能对我有用。
  • 我已经编辑了我的问题。我认为您可能必须了解我的问题的确切情况
  • 请立即查看编辑后的答案。它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 2021-03-12
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多