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


Answers:


231
  • 将ISO8601字符串转换为日期

    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)!
    
  • 从日期获取年,月,日和小时的日期部分

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
    
  • 最后创建一个新Date对象并删除分钟和几秒钟

    let finalDate = calendar.date(from:components)

还请考虑ISO8601DateFormatteriOS 10 / macOS 12中引入的便捷格式化程序:

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

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

3
“ yyyy-MM-dd'T'HH:mm:ssZ”中的Z解决了对我
不起作用的

我只想年份和月份,但这对我不起作用
Sneha

@Sneha如果您不想浪费时间.hour
vadian

@vadian我做到了,但我没有得到
Sneha

1
合而为一:ISO8601DateFormatter()。date(来自:“您的字符串”)!
Mike Irving,

38

请尝试以下日期格式。

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

希望能帮助到你..

斯威夫特4.1:

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

10
尝试过,日期之后返回nil。
asheyla

1
无法强制将'String'类型的值转换为'Date'类型
Oleksandr

22

在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
}

16

斯威夫特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 str = dateFormatter.string(from: self)

        return str
    }
}

9

嗨,您有单独的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

只要您通过了您dateformate和您的约会,您就会得到Year,month,day,hour额外信息

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

4

使全局功能

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



 

1
您认为您的输入和输出相同吗?
Deepak Carpenter

2

很快,

    var 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


2

只需第1步>从JSON或dataSource获取String值

步骤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)

1

Swift5。要查看是否已通过日期:

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

1

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

请参阅下面的解决方案。

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

    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

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的“区域设置”。


0

只需使用SwifterSwift。

stringDate = "2020-04-26T08:56:17.987Z"
let date = Date(iso8601String: stringDate)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.