【问题标题】:Convert date time to time only仅将日期时间转换为时间
【发布时间】:2016-12-22 12:42:22
【问题描述】:

我有这样的日期字符串:- 2016-12-20T15:26:21+11:00

需要什么样的DateFormatter(或其他)才能获得设备当前时区的时间。

【问题讨论】:

  • 你尝试过什么样的日期格式化程序?
  • yyyy-MM-dd hh:mm:ss a
  • 里面有日期,我以为你只想要时间?
  • 是的,只有时间。但在设备的时区。我不想使用:- componentsSeparatedBy 方法
  • 您不需要这样做,只需使用格式字符串中的时间分量即可。

标签: ios swift3 nsdate nsdateformatter


【解决方案1】:

输入是ISO8601,一个合适的解决方案是DateFormatter。如果没有针对 localetimeZone 的特定设置,格式化程序会考虑当前的语言环境和时区。

let dateString = "2016-12-20T15:26:21+11:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
let date = formatter.date(from:dateString)
formatter.timeStyle = .medium
formatter.dateStyle = .none
print(formatter.string(from: date!))

【讨论】:

  • 你能帮我找到这个格式吗:2019-05-23T10:21:20.044826-04:00
  • @pkc456 yyyy-MM-dd'T'HH:mm:ss.Sxxx,请看unicode.org/reports/tr35/…
  • 2019-11-20T00:00:00-05:00 的日期返回为零?我也检查了链接,但找不到格式。你能分享一下提到的日期字符串的日期格式化程序吗?
  • @pkc456 这与我的答案中的格式相同。请访问上面的链接并学习区分格式说明符。
【解决方案2】:

您可以使用以下代码将日期字符串转换为仅时间

       let sourceDateString = "2016-12-20T15:26:21+11:00"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        formatter.locale = Locale(identifier: "en-US")
        formatter.timeZone = TimeZone(identifier: "UTC")
        let date = formatter.date(from: sourceDateString)
        print("\(date)")

        formatter.timeZone = NSTimeZone.local
        formatter.dateFormat = "HH:mm:ss"

        let strDate = formatter.string(from: date!)
        print(strDate)

【讨论】:

    【解决方案3】:

    这是一种现代的方法。你可以在操场上试一试:

    let dateString = "2016-12-20T15:26:21+11:00"
    
    // First use an ISO8601 Date formatter to turn the string into a date.
    
    let inputFormatter = ISO8601DateFormatter()
    let date = inputFormatter.date(from: dateString)! // Force unwrapping as this is a demo - you should be more careful.
    
    // Now use a normal DateFormatter set to your current locale, turn of the date display, and use a short Time display style:
    
    let outputFormatter = DateFormatter()
    outputFormatter.locale = Locale.current
    outputFormatter.dateStyle = .none
    outputFormatter.timeStyle = .short
    
    let display = outputFormatter.string(from: date)
    
    // As I'm in the UK and the simulator local is US, I get "4:26 AM"
    // Your result will be different.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2020-12-05
      • 2019-09-22
      相关资源
      最近更新 更多