Swift日期格式

如何将这个日期时间从日期转换?

From this: 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)
494869 次浏览

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

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

编辑:获取输出2016年2月29日使用这个日期格式化器:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
你必须声明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 3级及以上:

从Swift 3中,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")
}

斯威夫特3

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

用新的Date对象代替NSDate斯威夫特3版本:

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之后建议

Swift - 5.0

let date = Date()
let format = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output format


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

Swift - 4.0

2018 - 02 - 01 - t19:10:04 + 0转换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!);
}
}

斯威夫特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"


}

带有Date扩展名的Swift 3

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")

Swift 3及以上

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale.current
print(dateFormatter.string(from: date)) // Jan 2, 2001
当你想本地化你的应用程序时,这也是有帮助的。Locale(identifier:)使用ISO 639-1代码。 另见苹果公司的文档

格式日期的另一个有趣的可能性。此截图属于苹果App“News”。

App截图

代码如下:

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()

这对于想要使用dateformatter.dateformat;

如果你想要12.09.18,你使用dateformatter.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

这里有一些替代方案:

  • 年代:G (AD), GGGG(阿诺多米尼)
  • 年:年(2018),年(18),年(2018)
  • 月:嗯,嗯,嗯,嗯,嗯
  • 月号:日,日
  • 星期名:E, EEEE, EEEEEE, EEEEEE

我解决了我的问题的格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(e。g 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!)
}

只需使用以下函数转换日期格式:-

  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
}

把它放在扩展中,并像下面这样调用它。它很容易在整个应用程序中使用。

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) ?? Date()


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

如果你想解析"1996-12-19T16:39:57-08:00"的日期,请使用以下格式"yyyy-MM-dd '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)

from Apple https://developer.apple.com/documentation/foundation/dateformatter

Swift 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)

对于Swift 4.2, 5

传递日期和格式为任何你想要的方式。 要选择格式,您可以访问NSDATEFORMATTER网站:

static func dateFormatter(date: Date,dateFormat:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: date)
}
    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!)
}

我建议默认添加时区。我将展示一个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

将@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)


iOS 15.0 +

iPadOS 15.0 +,

macOS 12.0 +,

Mac Catalyst 15.0+,

tvo 15.0 +,

watchOS 8.0 +,

Xcode 13.0 +

使用formatted(date:time:)

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

你可以使用另一个DateStyle来代替.abbreviated,比如.long.numeric或者定义一个自定义格式。


SwiftUI

 Text(myDate, format: Date.FormatStyle(date: .numeric, time: .omitted))

或者简单地使用:

 Text(myDate, style: .date)

参考

格式化(日期:时间:)

init(_:format:) . bref ="https://developer.apple.com/documentation/swiftui/text/init(_:format: "

文本。DateStyle < / >

在iOS 15中使用如下代码:

extension Date {
var string: String {
if #available(iOS 15.0, *) {
return self.formatted(date: .complete, time: .complete)
} else {
return self.description
}
}
}
class Utils {
class func dateFormatter(_ date: Date, _ format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: date)
}
}
print(Utils.dateFormatter(Date(), "EEEE, MMM d, yyyy"))

创建类名Utils导入相同的函数,您可以使用全局访问任何地方与您的日期和格式

这是一个完整的日期格式的swift扩展

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

func getFormattedDate(style: DateFormatter.Style) -> String {
let dateformat = DateFormatter()
dateformat.dateStyle = style
return dateformat.string(from: self)
}
}

使用

myDate.getFormattedDate(style: .medium) //medium, short, full, long

myDate.getFormattedDate(format: "yyyy/MM/dd HH:mm:ss")

Swift版本:5.6 +以上

dateformat的dateFormatter属性用于用自定义字符串模式格式化日期。

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

let date = dateFormatter.string(from: datePicker.date)
print(date)
//Feb 28, 2022

如果你想要任何不应该格式化和打印的东西,那么在这个单词周围使用单引号。像;‘at’

dateFormatter.dateFormat = "MMM dd, yyyy 'at' hh:MM a"
// May 29, 2022 at 12:05 PM

这些都是可能的模式格式DateTime &Time Zone

enter image description here