ios - 快速获取特定日期和时间的 UTC 时间?

标签 ios swift xcode datetime utc

大家好

我从 iOS 的日期选择器中选择了一个特定的日期和时间。我想将此日期和时间转换为 UTC 时间。我为此使用了以下函数。

func get_Date_time_from_UTC_time(string : String) -> String {

    let dateformattor = DateFormatter()
    dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC") as TimeZone!
    let dt = string
    let dt1 = dateformattor.date(from: dt as String)
    dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    dateformattor.timeZone = NSTimeZone.local
    return dateformattor.string(from: dt1!)
  }

我的位置在印度。因此,当我像 2016-12-26 09:53:45 这样传递时间时,它会给我 UTC 时间作为 2016-12-26 15:23:00 +0530。现在,当我在谷歌中搜索 UTC 时间时,它显示的时间为 12 月 26 日凌晨 4:32。请告诉我为什么会有这样的差异,我做的是否正确?

最佳答案

请您尝试使用以下代码: 因为根据我的理解,您应该首先提供您本地的时区以将您的日期转换为本地日期,然后再将其转换为 UTC:

func get_Date_time_from_UTC_time(string : String) -> String {

    let dateformattor = DateFormatter()
    dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateformattor.timeZone = NSTimeZone.local
    let dt = string
    let dt1 = dateformattor.date(from: dt as String)
    dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC") as TimeZone!
    return dateformattor.string(from: dt1!)
  }

我替换了 timeZone 代码。如果没有解决请检查并告诉我

关于ios - 快速获取特定日期和时间的 UTC 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41326460/

相关文章:

c++ - 如何链接使用 C++ vector 的 iOS 静态库,以便在 Delphi XE7 中使用?

ios - 无法从 Xcode 7.3.1 在设备 9.3.2 上安装应用程序

struct - Swift1.2 结构体初始化函数编译报错

ios - 如何禁用 UICollectionView 中的选择动画?

swift - 设置 `constraint.isActive = false` 是否解除约束?

ios - Xcode : Disable rotation for a view in the ViewController. swift

c++ - Boost Xcode C++ 命令行架构 x86_64 的 undefined symbol

ios - Xcode UI 测试 - 如何在 WebView 中查找和点击()元素

ios - 如何使用 DeviceCheck.DCDevice Xamarin Forms C# 生成 token 代码 iOS DeviceId

ios - 多个UITableViewCells在点击时会做不同的事情