Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert date into local time zone ios swift [duplicate]

Tags:

date

ios

swift

I'm working on date formatter, I got a response of date from server in string type, which I convert into date format but what I want to do is to convert a date and then manage according to local time.

For example, if 12/06/2017, 06:48:03 is a date from server and i'm from Pakistan so it gives me a date and time according to GMT+5 which is 12/06/2017, 11:48:03

Same as from India it gives me a date and time according to GMT+5:30 which is 12/06/2017, 12:18:03

Here is a source code

public class func converServerTimeStampToDate (_ timeStamp: String) -> Date {

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        let localDate = dateFormatter.date(from: timeStamp)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"

       // return dateFormatter.string(from: localDate!)
        return dateFormatter.date(from:dateFormatter.string(from: 
       localDate!))!

    }

Any help would be appreciated !!

like image 421
Nasir Javed Avatar asked Feb 04 '23 02:02

Nasir Javed


1 Answers

If you want the result to be a Date object just use the first part of @Intellij-Shivam's answer:

func serverToLocal(date:String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let localDate = dateFormatter.date(from: date)

    return localDate
}

(note that DateFormatter.date(from:) returns an optional, which is correct because the input date string might not be in the correct format.)

There is no such thing as a Date in your local time zone. Dates don't have a time zone. They record an instant in time all over the planet.

To display a date in your local time zone you can use the DateFormatter class method localizedString():

let dateString = DateFormatter.localizedString(
  inputDate, 
  dateStyle: .medium, 
  timeStyle: .medium)
like image 88
Duncan C Avatar answered Feb 10 '23 23:02

Duncan C