在Swift中将字符串转换为日期

时间:2016-04-26 10:06:17

标签: swift nsdate nsdateformatter

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

它中间的T确实抛弃了我在处理日期时所习惯的。

16 个答案:

答案 0 :(得分:118)

  • 将ISO8601 sting转换为日期

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

    获取年,月,日和小时的日期组件
    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

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

答案 1 :(得分:23)

请尝试以下日期格式。

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter. dateFromString (strDate)

希望有所帮助......

Swift 4.1:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.date(from: strDate)

答案 2 :(得分:9)

在Swift 4.1中你可以这样做:

func getDate() -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.locale = Locale.current
    return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}

答案 3 :(得分:7)

使全局功能

func convertDateFormat(inputDate: String) -> String {

     let olDateFormatter = DateFormatter()
     olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

     let oldDate = olDateFormatter.date(from: inputDate)

     let convertDateFormatter = DateFormatter()
     convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"

     return convertDateFormatter.string(from: oldDate!)
}

被调用的函数并在其中传递值

get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")

这是输出

Feb 25 2020 4:51 PM



 

答案 4 :(得分:6)

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ، d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let strMonth = dateFormatter.string(from: self)

        return strMonth
    }
}

答案 5 :(得分:5)

嗨您有单独的T格式,然后根据需要进行转换

// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
let timeStamp = dateFormatter.stringFromDate(date!)

答案 6 :(得分:3)

只要您传递dateformate和您的约会对象,即可获得Year,month,day,hourExtra info

func GetOnlyDateMonthYearFromFullDate(currentDateFormate:NSString , conVertFormate:NSString , convertDate:NSString ) -> NSString
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = currentDateFormate as String
        let formatter = NSDateFormatter()
        formatter.dateFormat = Key_DATE_FORMATE as String
        let finalDate = formatter.dateFromString(convertDate as String)
        formatter.dateFormat = conVertFormate as String
        let dateString = formatter.stringFromDate(finalDate!)

        return dateString
    }


获取年份

let Year = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "YYYY", convertDate: "2016-04-14T10:44:00+0000") as String


获得月份

let month = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "MM", convertDate: "2016-04-14T10:44:00+0000") as String


获取日

let day = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "dd", convertDate: "2016-04-14T10:44:00+0000") as String


获取时间

let hour  = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "hh", convertDate: "2016-04-14T10:44:00+0000") as String

答案 7 :(得分:3)

在swift4中,

    let Msg_Date_ = "2019-03-30T05:30:00+0000"

    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd yyyy h:mm a"  //"MMM d, h:mm a" for  Sep 12, 2:11 PM
    let datee = dateFormatterGet.date(from: Msg_Date_)
    Msg_Date_ =  dateFormatterPrint.string(from: datee ?? Date())

    print(Msg_Date_)

//输出:-Mar 30 2019 05:30 PM

答案 8 :(得分:2)

我也对这种格式感到疯狂。

请参阅下面的解决方案。

来自您的背部或其他来源的字符串:

    let isoDate = "2020-05-06 20:00:00-03"

确定日期格式

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!

现在将日期作为Date(),您可以使用formatDate.string

更改为所需的任何格式。
    let formatDate = DateFormatter()
    formatDate.dateFormat = "dd/MM/yyyy HH:mm"
    let drawDate = formatDate.string(from: date)
    print(drawDate)

输出:

    06/05/2020 20:00

答案 9 :(得分:1)

有时,将字符串迅速转换为Date可能导致返回nil,因此您应该添加“!”标记为format.date函数!

let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"

let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!

答案 10 :(得分:0)

请使用ISO8601解析库进行此操作。字符串编码的方式太多。不要依赖特定格式,也不要依赖服务器发送总是相同的格式。问题从结尾处的“ Z”开始,并将扩展到该标准的所有变体。解析库将处理所有情况,并始终提供安全的转换-而固定的格式字符串将来可能会失败。

您可以使用这些库之一。它们也可以在CococaPods上使用:

https://github.com/boredzo/iso-8601-date-formatter/

https://github.com/malcommac/SwiftDate

看一下实现。它们都有几百行,这是有充分理由的。

关于该问题:您可以使用NSDateComponents从日期中提取日期组件。网站上的示例完全涵盖了您的情况。

https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc

请注意,转换日期将考虑时区。您可能要显式设置NSCalendar的“区域设置”。

答案 11 :(得分:0)

正义 步骤1> 从JSON或dataSource获取字符串值

第2步>创建一个局部变量并分配它。

let startDate = CurrentDashBoard.startdate

步骤3>创建DateFormatter的实例。

let dateFormatter = DateFormatter()

步骤4> 从dateFormatter调用dateFormat并提供保存的日期dataType。

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")

步骤5> 将Local变量分配给该变量以进行转换。

let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate

步骤6> 通过以下代码提供所需的日期格式。

dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"

步骤6>将其分配给标签/文本

cell.lblStartDate.text = String(format: "%@", strstartDate)

代码:

let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate : 
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)

答案 12 :(得分:0)

快速5.查看是否通过了日期:

let expiryDate = "2020-01-10" // Jan 10 2020

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
    print("Not Yet expiryDate")
} else {
    print("expiryDate has passed")
}

答案 13 :(得分:0)

只需使用SwifterSwift。

maskPreds = model.predict(np.vstack(faces))

答案 14 :(得分:0)

从 iOS 15.0 开始,我们可以优雅地将字符串转换为日期:

let strategy = Date.ParseStrategy(format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits)T\(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits):\(second: .twoDigits)\(timeZone: .iso8601(.short))", timeZone: .current)
let date = try? Date("2016-04-14T10:44:00+0000", strategy: strategy)

答案 15 :(得分:0)

使用字符串扩展名快速将字符串转换为日期 斯威夫特 - 5.0

    extension String {
         public enum DateFormatType {
        
        /// The ISO8601 formatted year "yyyy" i.e. 1997
        case isoYear
        
        /// The ISO8601 formatted year and month "yyyy-MM" i.e. 1997-07
        case isoYearMonth
        
        /// The ISO8601 formatted date "yyyy-MM-dd" i.e. 1997-07-16
        case isoDate
        
        /// The ISO8601 formatted date and time "yyyy-MM-dd'T'HH:mmZ" i.e. 1997-07-16T19:20+01:00
        case isoDateTime
        
        /// The ISO8601 formatted date, time and sec "yyyy-MM-dd'T'HH:mm:ssZ" i.e. 1997-07-16T19:20:30+01:00
        case isoDateTimeSec
        
        /// The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ss.SSSZ" i.e. 1997-07-16T19:20:30.45+01:00
        case isoDateTimeMilliSec
        
        /// The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/"
        case dotNet
        
        /// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
        case rss
        
        /// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200"
        case altRSS
        
        /// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
        case httpHeader
        
        /// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy"
        case standard
        
        /// A custom date format string
        case custom(String)
        
        /// The local formatted date and time "yyyy-MM-dd HH:mm:ss" i.e. 1997-07-16 19:20:00
        case localDateTimeSec
        
        /// The local formatted date  "yyyy-MM-dd" i.e. 1997-07-16
        case localDate
        
        /// The local formatted  time "hh:mm a" i.e. 07:20 am
        case localTimeWithNoon
        
        /// The local formatted date and time "yyyyMMddHHmmss" i.e. 19970716192000
        case localPhotoSave
        
        case birthDateFormatOne
        
        case birthDateFormatTwo
        
        ///
        case messageRTetriveFormat
        
        ///
        case emailTimePreview
        
        var stringFormat:String {
          switch self {
          //handle iso Time
          case .birthDateFormatOne: return "dd/MM/YYYY"
          case .birthDateFormatTwo: return "dd-MM-YYYY"
          case .isoYear: return "yyyy"
          case .isoYearMonth: return "yyyy-MM"
          case .isoDate: return "yyyy-MM-dd"
          case .isoDateTime: return "yyyy-MM-dd'T'HH:mmZ"
          case .isoDateTimeSec: return "yyyy-MM-dd'T'HH:mm:ssZ"
          case .isoDateTimeMilliSec: return "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
          case .dotNet: return "/Date(%d%f)/"
          case .rss: return "EEE, d MMM yyyy HH:mm:ss ZZZ"
          case .altRSS: return "d MMM yyyy HH:mm:ss ZZZ"
          case .httpHeader: return "EEE, dd MM yyyy HH:mm:ss ZZZ"
          case .standard: return "EEE MMM dd HH:mm:ss Z yyyy"
          case .custom(let customFormat): return customFormat
            
          //handle local Time
          case .localDateTimeSec: return "yyyy-MM-dd HH:mm:ss"
          case .localTimeWithNoon: return "hh:mm a"
          case .localDate: return "yyyy-MM-dd"
          case .localPhotoSave: return "yyyyMMddHHmmss"
          case .messageRTetriveFormat: return "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
          case .emailTimePreview: return "dd MMM yyyy, h:mm a"
          }
        }  
 }
        
 func toDate(_ format: DateFormatType = .isoDate) -> Date?{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format.stringFormat
        let date = dateFormatter.date(from: self)
        return date 
  }
 }

我们使用like

    string.toDate(.isoDate)
    "1997-05-24".toDate(.isoDate)