Home > front end >  Does dateFromServer return the current Timezone of the person?
Does dateFromServer return the current Timezone of the person?

Time:01-24

When I am running the code below the date and time returned are in correct format but just not from what's coming from the API which in this case is the currentVehicle.LastCommunicationDate! Instead of coming the time from the currentVehicle.LastCommunicationDate! it's just returning a random timezone I think that is getting from the Server or something like that.

The output of the code I have right now is: 2022-01-21 02:04:15 when it should have been the live time in my local timezone but it's getting a different timezone.

The LastCommunicationDate coming from postman is in json format: "LastCommunicationDate": "2022-01-21T10:58:21.367",

The time i want to be is the one from Postman just converted from json to normal time like: yyyy-MM-dd HH:mm:ss

    let timeinterval : TimeInterval = (currentVechicle.LastCommunicationDate! as NSString).doubleValue
    let dateFromServer = NSDate(timeIntervalSinceNow:timeinterval)
    let outFormatter = DateFormatter()
    outFormatter.locale = Locale(identifier: "en_Al")
    print(dateFromServer)
    let dateFormater = outFormatter
    outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    print(dateFormater.string(from: dateFromServer as Date))
    let dateFromServers = dateFormater.string(from: dateFromServer as Date)

CodePudding user response:

LastCommunicationDate is a string, but you are converting it to a Double. Try this instead:

let lastCommunicationDate = "2022-01-21T10:58:21.367"

//Create dateformatter to convert string to Date
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [
    .withFullDate,
    .withTime,
    .withColonSeparatorInTime,
    .withFractionalSeconds
]

let isoDateFormatter2 = ISO8601DateFormatter()
isoDateFormatter2.formatOptions = [
    .withFullDate,
    .withTime,
    .withColonSeparatorInTime
]
let date = isoDateFormatter.date(from: lastCommunicationDate) ?? isoDateFormatter2.date(from: lastCommunicationDate)

//Create dateformatter to format date for output
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_Al")
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFromServers = outFormatter.string(from: date!)
  •  Tags:  
  • Related