development

Swift에서 문자열을 날짜로 변환

big-blog 2020. 10. 4. 11:57
반응형

Swift에서 문자열을 날짜로 변환


이 문자열을 "2016-04-14T10:44:00+0000"변환 NSDate하고 연도, 월, 일, 시간 만 유지하려면 어떻게해야합니까?

T그것의 중간에 정말 내가 날짜로 작업 할 때 사용하고있는 무슨 오프가 발생합니다.


  • ISO8601 문자열을 날짜로 변환

    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)
    

ISO8601DateFormatteriOS 10 / macOS 12에 도입 된 편의 포맷터도 고려하십시오 .

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

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

다음 날짜 형식을 시도하십시오.

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)

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

안녕하세요 당신은 별도의 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!)

당신 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

swift4에서

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

//output :- Mar 30 2019 05:30 PM


Please use an ISO8601 parsing library for doing this. There are too many ways how the string could be encoded. Don't rely on a specific format and don't rely on the server sending always the same. The problems start with the 'Z' at the end and it will extend through all varieties of the standard. A parsing library will handle all cases and will always provide a safe conversion - whereas a fixed formatting string is likely to fail in the future.

You could use one of these libraries. They are also available on CococaPods:

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

https://github.com/malcommac/SwiftDate

Take a look at the implementations. They are both several hundred lines long - for good reason.

With regards to the question: You can pull out the date components from the date using NSDateComponents. The example on the website covers exactly your case.

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

Please be aware, that converting your date will take into account the time zone. You might want to set the 'locale' of the NSCalendar explicitly.

참고URL : https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift

반응형