IT story

문자열 날짜를 NSDate로 변환하려면 어떻게해야합니까?

hot-time 2020. 5. 11. 08:06
반응형

문자열 날짜를 NSDate로 변환하려면 어떻게해야합니까?


이 문자열 날짜 "2014-07-15 06 : 55 : 14.198000 + 00 : 00"을 Swift의 NSDate로 변환하고 싶습니다.


이 시도:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

추가 쿼리 는 Objective-C 및 Swift에 대한 Foundation 프레임 워크 NSDateFormatterDateFormatter 클래스를 각각 확인하십시오.

스위프트 3 이상 (Swift 4 포함)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here

스위프트 4

import Foundation

let dateString = "2014-07-15" // change to your date format

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: dateString)
println(date)

스위프트 3

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

이 코드로 할 수 있습니다.


 func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}

스위프트 3을 위해 업데이트되었습니다.

func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

세부

  • 스위프트 4, Xcode 9.2
  • 스위프트 5, Xcode 10.2 (10E125)

해결책

import Foundation

extension DateFormatter {

    convenience init (format: String) {
        self.init()
        dateFormat = format
        locale = Locale.current
    }
}

extension String {

    func toDate (dateFormatter: DateFormatter) -> Date? {
        return dateFormatter.date(from: self)
    }

    func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
        guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
        return DateFormatter(format: outputFormat).string(from: date)
    }
}

extension Date {

    func toString (dateFormatter: DateFormatter) -> String? {
        return dateFormatter.string(from: self)
    }
}

용법

var dateString = "14.01.2017T14:54:00"
let dateFormatter = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss")
let date = Date()

print("original String with date:               \(dateString)")
print("date String() to Date():                 \(dateString.toDate(dateFormatter: dateFormatter)!)")
print("date String() to formated date String(): \(dateString.toDateString(dateFormatter: dateFormatter, outputFormat: "dd MMMM")!)")
let dateFormatter2 = DateFormatter(format: "dd MMM HH:mm")
print("format Date():                           \(date.toString(dateFormatter: dateFormatter2)!)")

결과

여기에 이미지 설명을 입력하십시오

추가 정보

날짜 형식에 대하여


문자열을 날짜로 자주 구문 분석해야 할 경우 기능을 확장으로 옮길 수 있습니다. sharedCode.swift 파일을 만들고 내 확장명을 거기에 넣었습니다.

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

그런 다음 문자열을 NSDate로 변환하려면 다음과 같이 작성할 수 있습니다.

var myDate = myDateString.toDateTime()

스위프트 3

func stringToDate(_ str: String)->Date{
    let formatter = DateFormatter()
    formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
    return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
    var dateFormatter = DateFormatter()
    dateFormatter.timeStyle=DateFormatter.Style.short
    return dateFormatter.string(from: str)
}

The code fragments on this QA page are "upside down"...

The first thing Apple mentions is that you cache your formatter...

Link to Apple doco stating exactly how to do this:

Cache Formatters for Efficiency Creating a date formatter is not a cheap operation. ...cache a single instance...

Use a global...

let df : DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter 
}()

Then simply use that formatter anywhere...

let s = df.string(from: someDate)

or

let d = df.date(from: someString)

Or use any of the other many, many convenient methods on DateFormatter.

It is that simple.

(If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)

Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.


Swift support extensions, with extension you can add a new functionality to an existing class, structure, enumeration, or protocol type.

You can add a new init function to NSDate object by extenging the object using the extension keyword.

extension NSDate
{
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "yyyyMMdd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
} 

Now you can init a NSDate object using:

let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")

Since Swift 3, many of the NS prefixes have been dropped.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
/* date format string rules
 * http://userguide.icu-project.org/formatparse/datetime
 */

let date = dateFormatter.date(from: dateString)

Swift 3,4:

2 useful conversions:

string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date

Usage: 1.

let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)

2.

 let someDateInString = "23.06.2017"
 var getDateFromString = dateFormatter.date(from: someDateInString)

FOR SWIFT 3.1

func convertDateStringToDate(longDate: String) -> String{

    /* INPUT: longDate = "2017-01-27T05:00:00.000Z"
     * OUTPUT: "1/26/17"
     * date_format_you_want_in_string from
     * http://userguide.icu-project.org/formatparse/datetime
     */

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

    if date != nil {

        let formatter = DateFormatter()
        formatter.dateStyle = .short
        let dateShort = formatter.string(from: date!)

        return dateShort

    } else {

        return longDate

    }
}

NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR


To add String within Date Format in Swift, I did this

 var dataFormatter:NSDateFormatter = NSDateFormatter()
                dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

This work for me..

    import Foundation
    import UIKit

    //dateString = "01/07/2017"
    private func parseDate(_ dateStr: String) -> String {
            let simpleDateFormat = DateFormatter()
            simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
            let dateFormat = DateFormatter()
            dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return

            let date = simpleDateFormat.date(from: dateStr)
            return dateFormat.string(from: date!)
    }

Below are some string to date format converting options can be usedin swift iOS.

  1. Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
  2. 12/27/2018 format= MM/dd/yyyy
  3. 12-27-2018 09:59 format= MM-dd-yyyy HH:mm
  4. Dec 27, 9:59 AM format= MMM d, h:mm a
  5. December 2018 format= MMMM yyyy
  6. Dec 27, 2018 format= MMM d, yyyy
  7. Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
  8. 2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
  9. 27.12.18 format= dd.MM.yy
  10. 09:59:19.815 format= HH:mm:ss.SSS

Swift: iOS
if we have string, convert it to NSDate,

var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"

// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)

if you have and date picker parse date like this

// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}

You can try this swift code

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"//same as strDate date formator
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")//Must used if you get one day less in conversion
    let convertedDateObject = dateFormatter.date(from: strDate)

import Foundation

let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter

date = dateFormatter.dateFromString(now)

date // $R6: __NSDate = 2014-07-16 03:03:34 PDT

https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32

참고 URL : https://stackoverflow.com/questions/24777496/how-can-i-convert-string-date-to-nsdate

반응형