Swift中的日期格式

时间:2016-02-29 13:02:20

标签: ios swift nsdate nsdateformatter

如何从日期转换此日期时间?

  

由此:2016-02-29 12:24:26
   至:2016年2月29日

到目前为止,这是我的代码,它返回一个nil值:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date: NSDate? = dateFormatter.dateFromString("2016-02-29 12:24:26")
print(date)

20 个答案:

答案 0 :(得分:165)

您必须声明2个不同的NSDateFormatters,第一个将字符串转换为NSDate,第二个以您的格式打印日期。
试试这段代码:

let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))

Swift 4:

在Swift 3/4 NSDate中,课程已更改为DateNSDateFormatter更改为DateFormatter

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

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

答案 1 :(得分:58)

这对于想使用dateformater.dateformat的人可能很有用; 如果您想使用12.09.18,请使用dateformater.dateformat = "dd.MM.yy"

Wednesday, Sep 12, 2018           --> EEEE, MMM d, yyyy
09/12/2018                        --> MM/dd/yyyy
09-12-2018 14:11                  --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM                   --> MMM d, h:mm a
September 2018                    --> MMMM yyyy
Sep 12, 2018                      --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000   --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000          --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18                          --> dd.MM.yy
10:41:02.112                      --> HH:mm:ss.SSS

答案 2 :(得分:36)

Swift 4和Xcode 9

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.string(from: date)) // Jan 2, 2001

当您想要本地化您的应用时,这也很有用。 Locale(标识符:)使用ISO 639-1 Code。 另请参阅Apple Documentation

答案 3 :(得分:33)

使用新Date对象的

Swift 3 版本代替NSDate

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

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"

let date: Date? = dateFormatterGet.date(from: "2017-02-14 17:24:26")
print(dateFormatter.string(from: date!))

编辑:mitul-nakum建议之后

答案 4 :(得分:25)

Swift - 4.0

2018-02-02 06:50:16 +0000 转换 02-02-2018

 extension Date {
   static func getFormattedDate(string: String) -> String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // This formate is input formated .

        let formateDate = dateFormatter.date(from:"2018-02-02 06:50:16 +0000")!
        dateFormatter.dateFormat = "dd-MM-yyyy" // Output Formated

        print ("Print :\(dateFormatter.string(from: formateDate))")//Print :02-02-2018
        return dateFormatter.string(from: formateDate)
    }
}

Swift - 4.0

2018-02-01T19:10:04 + 00:00 转换 2018年2月1日

extension Date {
    static func getFormattedDate(string: String , formatter:String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "MMM dd,yyyy"

        let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
        print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
        return dateFormatterPrint.string(from: date!);
    }
}

答案 5 :(得分:15)

swift 3

let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)

答案 6 :(得分:7)

Swift 3,Date分机号

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

然后你可以像这样使用它:

let date = Date()
date.string(with: "MMM dd, yyyy")

答案 7 :(得分:6)

我用以下格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(例如2018-06-15T00:00:00.000Z)解决了这个问题:

func formatDate(date: String) -> String {
   let dateFormatterGet = DateFormatter()
   dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

   let dateFormatter = DateFormatter()
   dateFormatter.dateStyle = .medium
   dateFormatter.timeStyle = .none
   //    dateFormatter.locale = Locale(identifier: "en_US") //uncomment if you don't want to get the system default format.

   let dateObj: Date? = dateFormatterGet.date(from: date)

   return dateFormatter.string(from: dateObj!)
}

答案 8 :(得分:6)

快速4、4.2和5

func getFormattedDate(date: Date, format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: date)
}

let formatingDate = getFormattedDate(date: Date(), format: "dd-MMM-yyyy")
        print(formatingDate)

答案 9 :(得分:3)

    import UIKit
    // Example iso date time
    let isoDateArray = [
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39Z",
        "2020-03-18T07:32:39.8Z",
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39.8834Z"
    ]


    let dateFormatterGetWithMs = DateFormatter()
    let dateFormatterGetNoMs = DateFormatter()

// Formater with and without millisecond 
    dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd,yyyy"

    for dateString in isoDateArray {
        var date: Date? = dateFormatterGetWithMs.date(from: dateString)
        if (date == nil){
            date = dateFormatterGetNoMs.date(from: dateString)
        }
        print("===========>",date!)
    }

答案 10 :(得分:2)

格式化日期的另一种可能。此屏幕截图属于Apple的应用程序“新闻”。

App screenshot

代码如下:

let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())

let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())

let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())

let stringDate = String(format: "%@\n%@ %@", stringDay.uppercased(), stringMonth.uppercased(), numDay)

没有任何东西可以添加到lorenzoliveto提出的替代方案中。太完美了。

let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()

答案 11 :(得分:2)

要将2016-02-29 12:24:26转换为日期,请使用此日期格式化程序:

\n

编辑:要获得输出2016年2月29日,请使用此日期格式化程序:

<setBody>
  <simple>one line\nsecond line</simple>
</setBody>

答案 12 :(得分:2)

只需使用以下功能即可转换日期格式:-

  let convertedFormat =  convertToString(dateString: "2019-02-12 11:23:12", formatIn: "yyyy-MM-dd hh:mm:ss", formatOut: "MMM dd, yyyy")    //calling function

   print(convertedFormat) // feb 12 2019


 func convertToString (dateString: String, formatIn : String, formatOut : String) -> String {

    let dateFormater = DateFormatter()
    dateFormater.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
    dateFormater.dateFormat = formatIn
    let date = dateFormater.date(from: dateString)

    dateFormater.timeZone = NSTimeZone.system

    dateFormater.dateFormat = formatOut
    let timeStr = dateFormater.string(from: date!)
    return timeStr
 }

答案 13 :(得分:2)

对于Swift 4.2,5

按照您希望的方式传递日期和格式。 要选择您可以访问的格式,NSDATEFORMATTER website

static func dateFormatter(date: Date,dateFormat:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    return dateFormatter.string(from: date)
}

答案 14 :(得分:2)

转换@BatyrCan可以使用其他格式回答Swift 5.3。在Xcode 12中进行了测试。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!

dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000

dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600

dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16

dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM

dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000

dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000

dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000

dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM

dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000

dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00

//Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm

// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)

答案 15 :(得分:0)

将其放在扩展名中,然后按以下方式调用。在整个应用程序中都很容易使用。

self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")

实施

func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = currentFomat

        let date : Date = dateFormatterGet.date(from: strDate)!

        dateFormatterGet.dateFormat = expectedFromat
        return dateFormatterGet.string(from: date)
    }

答案 16 :(得分:0)

如果您想解析“ 1996-12-19T16:39:57-08:00”中的日期,请使用以下格式“ yyyy-MM-dd'T'HH:mm:ssZZZZZ”:

let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)

来自苹果https://developer.apple.com/documentation/foundation/dateformatter

答案 17 :(得分:0)

swift 3

func dataFormat(dataJ: Double) -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .none
        let date = Date(timeIntervalSince1970: dataJ)
        return (dataJ != nil) ? "Today, \(dateFormatter.string(from: date))" : "Date Invalid"

    }

答案 18 :(得分:0)

我建议默认添加时区。我将举一个Swift 5的例子
1.新建一个扩展文件Date+Formatter.swift

import Foundation

extension Date {
    func getFormattedDateString(format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = TimeZone.current
        return dateFormatter.string(from: self)
    }
}
  1. 用法示例
    let date = Date()
    let dateString = date.getFormattedDateString(format: "yyyy-MM-dd HH:mm:ss")
    print("dateString > \(dateString)")
    // print
    // dateString > 2020-04-30 15:15:21

答案 19 :(得分:0)

Swift 5.5+

使用formatted(date:time:)

let now = Date.now
let date = now.formatted(date: .abbreviated, time: .omitted)

您可以使用 DateStyle(例如 .abbreviated.long)或定义自定义格式来代替 .numeric

https://developer.apple.com