codememo

Swift에서 날짜를 밀리초 단위로 표시하고 다시 날짜로 표시합니다.

tipmemo 2023. 8. 16. 22:23
반응형

Swift에서 날짜를 밀리초 단위로 표시하고 다시 날짜로 표시합니다.

현재 시간을 UTC로 계산하고 나노초 단위로 입력한 다음 나노초 단위로 계산하여 현지 시간으로 다시 날짜를 지정해야 합니다.

시간을 나노초로 보내고 다시 날짜 문자열로 되돌릴 수 있지만 문자열에서 날짜로 이동하면 시간이 복잡해집니다.

//Date to milliseconds
func currentTimeInMiliseconds() -> Int! {
    let currentDate = NSDate()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: dateFormatter.string(from: currentDate as Date))
    let nowDouble = date!.timeIntervalSince1970
    return Int(nowDouble*1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds(format:String) -> Date {
        let date : NSDate! = NSDate(timeIntervalSince1970:Double(self) / 1000.0)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = TimeZone.current
        let timeStamp = dateFormatter.string(from: date as Date)
    
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return ( formatter.date( from: timeStamp ) )!
    }
}

타임스탬프는 맞지만 반환된 날짜는 아닙니다.

왜 끈으로 뭘 하는지 이해가 안가요

extension Date {
    var millisecondsSince1970:Int64 {
        Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }
    
    init(milliseconds:Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}


Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)

@Travis 솔루션이 작동하지만 경우에 따라서는

var millisecondsSince1970:Int 충돌 작동을 유발합니다.

실수로

이중 이 발생하면 결과가 Int.max보다 크기 때문에 Int로 변환할 수 없습니다. Int64로 답변을 업데이트하십시오.

다음은 업데이트된 답변입니다.

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

Int 정의 정보.

32비트 플랫폼에서는 Int32와 크기가 같고 64비트 플랫폼에서는 Int64와 크기가 같습니다.

저는 이 를 일적으로이, 는문접합다니에서 .iPhone 5env.32에서 됩니다.새 장치는 이제 64비트 환경을 실행합니다.의 그들.Int▁▁be 될 것입니다.Int64.

같은 문제를 가진 사람에게도 도움이 되길 바랍니다.

@Travis 솔루션은 맞지만 날짜가 생성되면 밀리초가 손실됩니다.날짜에 밀리초를 포함하는 줄을 추가했습니다.

이 정밀도가 필요하지 않으면 Travis 솔루션을 사용하십시오. 더 빠를 것이기 때문입니다.

extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}
//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
    let currentDate = Date()
    let since1970 = currentDate.timeIntervalSince1970
    return Int(since1970 * 1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds() -> Date {
        return Date(timeIntervalSince1970: TimeInterval(self)/1000)
    }
}

는 문자열을 변환을 했고, 그 임의의 변환들을 제거했습니다.!.

let dateTimeStamp = NSDate(timeIntervalSince1970:Double(currentTimeInMiliseconds())/1000)  //UTC time  //YOUR currentTimeInMiliseconds METHOD
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
print("Local Time", strDateSelect) //Local time


let dateFormatter2 = NSDateFormatter()
dateFormatter2.timeZone = NSTimeZone(name: "UTC") as NSTimeZone!
dateFormatter2.dateFormat = "yyyy-MM-dd"

let date3 = dateFormatter.dateFromString(strDateSelect)
print("DATE",date3)

@Prashant Tukadiya 대답은 효과가 있습니다.그러나 UserDefaults에 값을 저장한 다음 다른 날짜와 비교하려면 int64가 잘려서 문제가 발생할 수 있습니다.해결책을 찾았어요

스위프트 4:

UserDefaults에서 int64를 문자열로 저장할 수 있습니다.

let value: String(Date().millisecondsSince1970)
let stringValue = String(value)
UserDefaults.standard.set(stringValue, forKey: "int64String")

당신은 방해를 피하는 것처럼.

그러면 원래 값을 복구할 수 있습니다.

let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!)

이를 통해 다른 날짜 값과 비교할 수 있습니다.

let currentTime = Date().millisecondsSince1970
let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!) ?? 0 

if currentTime < originalValue {
     return false
} else {
     return true
}

이것이 같은 문제를 가진 사람에게 도움이 되기를 바랍니다.

UInt64에서 시간 토큰을 얻기 위한 간단한 한 줄 코드

let time = UInt64(Date().timeIntervalSince1970 * 1000)

print(time) <----- prints time in UInt64

추가 팁:

1970년 이후 API 호출에 대해 10자리 밀리초의 타임스탬프인 경우

let timeStamp = Date().timeIntervalSince1970

print(timeStamp) <-- prints current time stamp

Swift 5/iOS 13의 간단한 솔루션은 다음과 같습니다.

extension Date {
    
    func toMilliseconds() -> Int64 {
        Int64(self.timeIntervalSince1970 * 1000)
    }

    init(milliseconds:Int) {
        self = Date().advanced(by: TimeInterval(integerLiteral: Int64(milliseconds / 1000)))
    }
}

이는 UTC 시간과 현지 시간 간의 차이를 계산하고 밀리초 단위로 조정하여 계산한 것으로 가정합니다.때는 이위해, 용사를 합니다.Calendar.

var cal = Calendar.current
cal.timeZone = TimeZone(abbreviation: "UTC")!
let difference = cal.compare(dateGiven, to: date, toGranularity: .nanosecond)

변환 후 날짜를 비교할 것인지 주의하십시오!

예를 들어, 날짜가 TimeInterval(366144731.9)이고 밀리초 Int64(1344451931900)로 변환된 시뮬레이터의 자산을 얻었습니다.간격(366144731.9000001), 사용

func convertToMilli(timeIntervalSince1970: TimeInterval) -> Int64 {
    return Int64(timeIntervalSince1970 * 1000)
}

func convertMilliToDate(milliseconds: Int64) -> Date {
    return Date(timeIntervalSince1970: (TimeInterval(milliseconds) / 1000))
}

creationDate로 자산을 가져오려고 했지만 자산을 찾을 수 없습니다. 여러분이 알 수 있듯이 숫자가 않습니다.

라운드(interval*1000)/1000, NSDecimalNumber 사용 등과 같이 두 배의 소수점 정밀도를 줄이기 위해 여러 솔루션을 시도했습니다.성공하지 못한

결국 creationDate == Interval 대신 interval -1 < creationDate < interval + 1로 가져오기로 했습니다.

더 나은 해결책이 있을지도 모릅니다!?

반드시 날짜를 정수로 변환해야 하는 경우를 제외하고,Double대신 시간 간격을 나타냅니다.결국, 이 유형은timeIntervalSince1970돌아온다.정수로 변환하는 모든 답변은 밀리초 미만의 정밀도를 보이지만 이 솔루션은 훨씬 더 정확합니다(부동점 정밀도로 인해 여전히 정밀도가 떨어집니다).

public extension Date {
    
    /// The interval, in milliseconds, between the date value and
    /// 00:00:00 UTC on 1 January 1970.
    /// Equivalent to `self.timeIntervalSince1970 * 1000`.
    var millisecondsSince1970: Double {
        return self.timeIntervalSince1970 * 1000
    }

    /**
     Creates a date value initialized relative to 00:00:00 UTC
     on 1 January 1970 by a given number of **milliseconds**.
     
     equivalent to
     ```
     self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
     ```
     - Parameter millisecondsSince1970: A time interval in milliseconds.
     */
    init(millisecondsSince1970 milliseconds: Double) {
        self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

언급URL : https://stackoverflow.com/questions/40134323/date-to-milliseconds-and-back-to-date-in-swift

반응형