Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift convert unix time to date and time

Tags:

time

ios

swift

My current code:

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

The results:

println(timeResult) = 1415639000.67457

println(NSDate()) = 2014-11-10 17:03:20 +0000 was just to test to see what NSDate was providing.

I want the first to look like the last. The value for dt = 1415637900.

Also, how can I adjust to time zone? Running on iOS.

like image 493
MwcsMac Avatar asked Nov 10 '14 17:11

MwcsMac


3 Answers

You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:

let date = NSDate(timeIntervalSince1970: 1415637900)
like image 126
Nate Cook Avatar answered Nov 07 '22 02:11

Nate Cook


To get the date to show as the current time zone I used the following.

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

Swift 3.0 Version

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

Swift 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)                                
}
like image 72
MwcsMac Avatar answered Nov 07 '22 02:11

MwcsMac


It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long

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)")
like image 30
Sachin Tyagi Avatar answered Nov 07 '22 04:11

Sachin Tyagi