在 Swift 中将字符串转换为日期 [英] Convert string to date in Swift

查看:121
本文介绍了在 Swift 中将字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将这个字符串 "2016-04-14T10:44:00+0000" 转换为 NSDate 并只保留年、月、日、小时?

How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour?

中间的 T 确实颠覆了我在处理日期时的习惯.

The T in the middle of it really throws off what I am used to when working with dates.

推荐答案

  • 将 ISO8601 字符串转换为日期

    • Convert the ISO8601 string to date

      let isoDate = "2016-04-14T10:44:00+0000"
      
      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
      dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
      let date = dateFormatter.date(from:isoDate)!
      

    • 从日期中获取年、月、日和小时的日期组件

    • Get the date components for year, month, day and hour from the date

      let calendar = Calendar.current
      let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
      

    • 最后创建一个新的Date对象并去掉分​​秒

      let finalDate = calendar.date(from:components)
      

    • 还要考虑 iOS 10/macOS 12 中引入的便利格式化程序 ISO8601DateFormatter:

      Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:

      let isoDate = "2016-04-14T10:44:00+0000"
      
      let dateFormatter = ISO8601DateFormatter()
      let date = dateFormatter.date(from:isoDate)!
      

      这篇关于在 Swift 中将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆