programing

유닉스 시간을 날짜 및 시간으로 신속하게 변환

javajsp 2023. 8. 17. 20:46

유닉스 시간을 날짜 및 시간으로 신속하게 변환

현재 코드:

if  let var timeResult = (jsonResult["dt"] as? Double) {
    timeResult = NSDate().timeIntervalSince1970
    println(timeResult)
    println(NSDate())
}

결과:

println(timeResult)= 1415639000.67457

println(NSDate())2014-11-10 17:03:20 +0000은 단지 무엇을 테스트하기 위한 것이었습니다.NSDate제공하고 있었습니다.

저는 첫 번째 것이 마지막 것처럼 보이기를 원합니다.dt = 1415637900의 값입니다.

또한 어떻게 하면 시간대에 적응할 수 있습니까?iOS에서 실행 중.

다음을 사용하여 해당 값을 가진 날짜를 얻을 수 있습니다.NSDate(withTimeIntervalSince1970:)이니셜라이저:

let date = NSDate(timeIntervalSince1970: 1415637900)

날짜를 현재 시간대로 표시하기 위해 다음을 사용했습니다.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

스위프트 3.0 버전

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

스위프트 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

유닉스 타임스탬프를 원하는 형식으로 변환하는 것은 간단합니다._ts가 UNIX 타임스탬프라고 가정합니다.

let date = NSDate(timeIntervalSince1970: _ts)

let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"

 let dateString = dayTimePeriodFormatter.stringFromDate(date)

  print( " _ts value is \(_ts)")
  print( " _ts value is \(dateString)")

Swift 3에서 날짜를 관리하기 위해 저는 다음과 같은 도우미 기능을 갖게 되었습니다.

extension Double {
    func getDateStringFromUTC() -> String {
        let date = Date(timeIntervalSince1970: self)

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateStyle = .medium

        return dateFormatter.string(from: date)
    }
}

이렇게 하면 필요할 때 언제든지 쉽게 사용할 수 있습니다. 저의 경우 문자열을 변환하고 있었습니다.

("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"

형식 지정에 대한 자세한 내용은 DateFormatter 문서를 참조하십시오(일부 예제는 구식입니다).

는 이 기사가 또한 매우 도움이 된다는 을 알았습니다.

여기 제 앱 중 하나에서 작동하는 Swift 3 솔루션이 있습니다.

/**
 * 
 * Convert unix time to human readable time. Return empty string if unixtime     
 * argument is 0. Note that EMPTY_STRING = ""
 *
 * @param unixdate the time in unix format, e.g. 1482505225
 * @param timezone the user's time zone, e.g. EST, PST
 * @return the date and time converted into human readable String format
 *
 **/

private func getDate(unixdate: Int, timezone: String) -> String {
    if unixdate == 0 {return EMPTY_STRING}
    let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
    let dayTimePeriodFormatter = DateFormatter()
    dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
    dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
    let dateString = dayTimePeriodFormatter.string(from: date as Date)
    return "Updated: \(dateString)"
}
func timeStringFromUnixTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)

    // Returns date formatted as 12 hour time.
    dateFormatter.dateFormat = "hh:mm a"
    return dateFormatter.stringFromDate(date)
}

func dayStringFromTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)
    dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(date)
}

인 스위프트 5

이 구현을 사용하면 매개 변수로 epoch 시간을 지정하면 다음과 같이 출력됩니다(1초 전, 2분 전 등).

func setTimestamp(epochTime: String) -> String {
    let currentDate = Date()
    let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)

    let calendar = Calendar.current

    let currentDay = calendar.component(.day, from: currentDate)
    let currentHour = calendar.component(.hour, from: currentDate)
    let currentMinutes = calendar.component(.minute, from: currentDate)
    let currentSeconds = calendar.component(.second, from: currentDate)

    let epochDay = calendar.component(.day, from: epochDate)
    let epochMonth = calendar.component(.month, from: epochDate)
    let epochYear = calendar.component(.year, from: epochDate)
    let epochHour = calendar.component(.hour, from: epochDate)
    let epochMinutes = calendar.component(.minute, from: epochDate)
    let epochSeconds = calendar.component(.second, from: epochDate)

    if (currentDay - epochDay < 30) {
        if (currentDay == epochDay) {
            if (currentHour - epochHour == 0) {
                if (currentMinutes - epochMinutes == 0) {
                    if (currentSeconds - epochSeconds <= 1) {
                        return String(currentSeconds - epochSeconds) + " second ago"
                    } else {
                        return String(currentSeconds - epochSeconds) + " seconds ago"
                    }

                } else if (currentMinutes - epochMinutes <= 1) {
                    return String(currentMinutes - epochMinutes) + " minute ago"
                } else {
                    return String(currentMinutes - epochMinutes) + " minutes ago"
                }
            } else if (currentHour - epochHour <= 1) {
                return String(currentHour - epochHour) + " hour ago"
            } else {
                return String(currentHour - epochHour) + " hours ago"
            }
        } else if (currentDay - epochDay <= 1) {
            return String(currentDay - epochDay) + " day ago"
        } else {
            return String(currentDay - epochDay) + " days ago"
        }
    } else {
        return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
    }
}


func getMonthNameFromInt(month: Int) -> String {
    switch month {
    case 1:
        return "Jan"
    case 2:
        return "Feb"
    case 3:
        return "Mar"
    case 4:
        return "Apr"
    case 5:
        return "May"
    case 6:
        return "Jun"
    case 7:
        return "Jul"
    case 8:
        return "Aug"
    case 9:
        return "Sept"
    case 10:
        return "Oct"
    case 11:
        return "Nov"
    case 12:
        return "Dec"
    default:
        return ""
    }
}

어떻게 부르죠?

setTimestamp(epochTime: time)원하는 출력을 문자열로 얻을 수 있습니다.

타임스탬프를 Date 개체로 변환합니다.

타임스탬프 개체가 올바르지 않으면 현재 날짜를 반환합니다.

class func toDate(_ timestamp: Any?) -> Date? {
    if let any = timestamp {
        if let str = any as? NSString {
            return Date(timeIntervalSince1970: str.doubleValue)
        } else if let str = any as? NSNumber {
            return Date(timeIntervalSince1970: str.doubleValue)
        }
    }
    return nil
}

스위프트:

extension Double {
    func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = dateStyle
        dateFormatter.timeStyle = timeStyle
        return dateFormatter.string(from: Date(timeIntervalSince1970: self))
    }
}

어쨌든 @Nate Cook의 답변은 받아들여지지만 더 나은 날짜 형식으로 개선하고 싶습니다.

Swift 2.2를 사용하면 원하는 형식의 날짜를 얻을 수 있습니다.

//TimeStamp
let timeInterval  = 1415639000.67457
print("time interval is \(timeInterval)")

//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)

//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is =  \(dateString)")

결과는

시간 간격은 1415639000.67457입니다.

서식 날짜는 = 10, 2014년 11월 17:03:PM입니다.

최대화하는 경우CodableJSON 데이터를 구문 분석하기 위한 프로토콜입니다.데이터 유형을 다음과 같이 간단하게 만들 수 있습니다.dt~하듯이Date수행:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970

본인: API에서 오는 타임스탬프를 유효한 날짜로 변환하는 중:

`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`

이 코드를 사용하여 변환할 수 있습니다.timeStamp시간 및 날짜까지

let timeStamp = Date().timeIntervalSince1970

let date = NSDate(timeIntervalSince1970: timeStamp)

let dayTimePeriodFormatter = DateFormatter()

dayTimePeriodFormatter.dateFormat = "dd MMMM,YYYY.hh:mm a"

let dateTimeString = dayTimePeriodFormatter.string(from: date as Date)

let dateTime = dateTimeString.split(separator: ".")

print( "Date = \(dateTime[0])")

print( "Time = \(dateTime[1])")

Output: 

Date = 19 January,2022

Time = 10:46 AM

언급URL : https://stackoverflow.com/questions/26849237/swift-convert-unix-time-to-date-and-time