Formatting date with Swift

后端 未结 2 1649
无人共我
无人共我 2021-01-23 04:09

I am trying to Convert a String into Date using Date Formatter .

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = \"yyyy-MM-dd’T’HH:mm:ss’Z’\"
va         


        
相关标签:
2条回答
  • 2021-01-23 04:35

    Try like this:

    let dateFormatter = NSDateFormatter()
    dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let availabletoDateTime = dateFormatter.dateFromString("2015-07-16T08:00:00Z")
    
    0 讨论(0)
  • 2021-01-23 04:47

    This looks like you're trying to use an ISO 8601/RFC 3339 date. Usually the date string will not include any quotes. It will be: something like 2015-07-16T08:00:00Z. FYI, the Z stands for GMT/UTC timezone (as opposed to your local timezone).

    So, in Swift 3:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    dateFormatter.locale = Locale(localeIdentifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    let availabletoDateTime = dateFormatter.date(from: "2015-07-16T08:00:00Z")
    

    Note, I'm (a) using ZZZZZ rather than Z in my format string; and (b) explicitly setting the timeZone. I do this for my formatter can not only successfully parse the string 2015-07-16T08:00:00Z into a Date object, but that it can also be used to go the other direction, converting a Date object into a string in the format like 2015-07-16T08:00:00Z.

    Also note I'm using ' character, not the character. Nor do I need to set the calendar, as locale of en_US_POSIX is all you need.

    For more information, see Technical Q&A 1480.


    Not, nowadays you'd use the new ISO8601DateFormatter:

    let dateFormatter = ISO8601DateFormatter()
    let availabletoDateTime = dateFormatter.date(from: "2015-07-16T08:00:00Z")
    

    In Swift 3, use this ISO8601DateFormatter, if you can, but recognize that it doesn't provide as much control (e.g. prior to iOS 11, you couldn't specify milliseconds). But in this case, it's sufficient.

    For Swift 2 rendition, see previous revision of this answer.

    0 讨论(0)
提交回复
热议问题