IT

신속한 Date 객체를 작성하는 방법

lottoking 2020. 7. 7. 07:24
반응형

신속한 Date 객체를 작성하는 방법


swift xcode의 날짜에서 날짜 객체를 어떻게 생성합니까?

예를 들어 자바 스크립트에서는 다음을 수행합니다. var day = new Date('2014-05-20');


스위프트는 자체 Date유형이 있습니다. 사용할 필요가 없습니다 NSDate.

Swift에서 날짜 및 시간 생성

Swift에서 날짜 및 시간은 2001 년 1 월 1 일 기준 날짜 00:00:00 UTC 이후 초 수를 측정하는 64 비트 부동 소수점 숫자로 저장됩니다 . 이것은 Date구조 로 표현됩니다 . 다음은 현재 날짜와 시간을 알려줍니다.

let currentDateTime = Date()

다른 날짜-시간을 만들려면 다음 방법 중 하나를 사용할 수 있습니다.

방법 1

2001 년 기준 날짜 이전 또는 이후의 시간 (초)을 알고 있으면이를 사용할 수 있습니다.

let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

방법 2

물론 년, 월, 일 및 시간 (상대 초가 아닌)을 사용하여을 만드는 것이 더 쉬울 것 Date입니다. 이를 위해 DateComponents구성 요소를 지정한 다음 Calendar날짜를 만드는 데 사용할 수 있습니다 . Calendar제공 Date컨텍스트를. 그렇지 않으면, 어떤 시간대 나 캘린더를 표시 할 것인지 어떻게 알 수 있습니까?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar.current // user calendar
let someDateTime = userCalendar.date(from: dateComponents)

다른 시간대 약어는 여기 에서 찾을 수 있습니다 . 비워두면 기본값은 사용자의 시간대를 사용하는 것입니다.

방법 3

가장 간결한 방법 (그러나 반드시 최고는 아님)을 사용할 수 있습니다 DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

유니 코드 기술 표준은 다른 형식으로 보여줄 것을 DateFormatter지원합니다.

노트

날짜와 시간을 읽을 수있는 형식으로 표시하는 방법에 대한 전체 답변참조하십시오 . 다음과 같은 훌륭한 기사를 읽으십시오.


이것은 기존 NSDate클래스 의 확장을 사용하여 가장 잘 수행됩니다 .

다음 확장은 지정된 형식의 날짜 문자열을 사용하여 현재 로케일로 날짜를 작성하는 새 초기화 프로그램을 추가합니다.

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

이제 다음을 수행하여 Swift에서 NSDate를 만들 수 있습니다.

NSDate(dateString:"2014-06-06")

이 구현은 NSDateFormatter를 캐시하지 않습니다. NSDateFormatter NSDate는 이런 방식으로 많은 파일을 생성 할 것으로 예상되는 경우 성능상의 이유로 할 수 있습니다 .

Please also note that this implementation will simply crash if you try to initialize an NSDate by passing in a string that cannot be parsed correctly. This is because of the forced unwrap of the optional value returned by dateFromString. If you wanted to return a nil on bad parses, you would ideally use a failible initializer; but you cannot do that now (June 2015), because of a limitation in Swift 1.2, so then you're next best choice is to use a class factory method.

A more elaborate example, which addresses both issues, is here: https://gist.github.com/algal/09b08515460b7bd229fa .


Update for Swift 5

extension Date {
    init(_ dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)!
        self.init(timeInterval:0, since:date)
    }
}

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

Here's how I did it in Swift 4.2:

extension Date {

    /// Create a date from specified parameters
    ///
    /// - Parameters:
    ///   - year: The desired year
    ///   - month: The desired month
    ///   - day: The desired day
    /// - Returns: A `Date` object
    static func from(year: Int, month: Int, day: Int) -> Date? {
        let calendar = Calendar(identifier: .gregorian)
        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day
        return calendar.date(from: dateComponents) ?? nil
    }
}

Usage:

let marsOpportunityLaunchDate = Date.from(year: 2003, month: 07, day: 07)

According to Apple documentation

Example :

var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

In, Swift 3.0 you have set date object for this way.

extension Date
{
    init(dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = Locale(identifier: "en_US_POSIX")
        let d = dateStringFormatter.date(from: dateString)!
        self(timeInterval:0, since:d)
    }
}

Personally I think it should be a failable initialiser:

extension Date {

    init?(dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        if let d = dateStringFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since: d)
        } else {
            return nil
        }
    }
}

Otherwise a string with an invalid format will raise an exception.


According to @mythz answer, I decide to post updated version of his extension using swift3 syntax.

extension Date {
    static func from(_ year: Int, _ month: Int, _ day: Int) -> Date?
    {
        let gregorianCalendar = Calendar(identifier: .gregorian)
        let dateComponents = DateComponents(calendar: gregorianCalendar, year: year, month: month, day: day)
        return gregorianCalendar.date(from: dateComponents)
    }
}

I don't use parse method, but if someone needs, I will update this post.


I often have a need to combine date values from one place with time values for another. I wrote a helper function to accomplish this.

let startDateTimeComponents = NSDateComponents()
startDateTimeComponents.year = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: date).year
startDateTimeComponents.month = NSCalendar.currentCalendar().components(NSCalendarUnit.Month, fromDate: date).month
startDateTimeComponents.day = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: date).day
startDateTimeComponents.hour = NSCalendar.currentCalendar().components(NSCalendarUnit.Hour, fromDate: time).hour
startDateTimeComponents.minute = NSCalendar.currentCalendar().components(NSCalendarUnit.Minute, fromDate: time).minute
let startDateCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
combinedDateTime = startDateCalendar!.dateFromComponents(startDateTimeComponents)!

참고URL : https://stackoverflow.com/questions/24089999/how-do-you-create-a-swift-date-object

반응형