Swift 3.0: Convert Server Utc Time to Local Time and Vice-Versa

Swift 3.0 : Convert server UTC time to local time and vice-versa

I don't know what's wrong with your code.
But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string.
Here is my small version of UTCToLocal and localToUTC function.
But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.

func localToUTC(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.calendar = Calendar.current
dateFormatter.timeZone = TimeZone.current

if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "H:mm:ss"

return dateFormatter.string(from: date)
}
return nil
}

func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "h:mm a"

return dateFormatter.string(from: date)
}
return nil
}

and call these function like below.

print(utcToLocal(dateStr: "13:07:00"))
print(localToUTC(dateStr: "06:40 PM"))

Hope this will help you.
Happy coding!!

How to Convert UTC time to local time In Swift 3?

Use TimeZone.current to detect local timezone and apply it.

let formatter = DateFormatter()
// initially set the format based on your datepicker date
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
//print(localTimeZoneAbbreviation)
formatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// convert your string to date
let yourDate = formatter.date(from: strDate)
//then again set the date format which type of output you need

In your function :

func convertStringDateFormateUTC(strDate: String,
strCurrentFormateType:String, strFormateType:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = strCurrentFormateType

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)

var strNewdate = NSDate()
strNewdate = dateFormatter.date(from: strDate)! as NSDate
dateFormatter.dateFormat = strFormateType;
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
return dateFormatter.string(from: strNewdate as Date)
}

How to convert Server UTC Time to local time in Swift 4?

Obviously, the key issue is the absence of the quotes around the T.

But you probably don’t want to instantiate a new date formatter every time you call this routine (because this is a notoriously computationally expensive process). So you should save your date formatter as a property. This way you don’t need to instantiate a new formatter for every string you want to convert to a Date. Likewise this formatter can be used to convert dates back to strings in the format of 2019-09-30T09:10:32.537244Z.

As such, contrary to advice provided elsewhere, I would suggest setting the timeZone of the formatter. It’s not needed when converting from strings to dates (because the date string contains the time zone qualifier), but when going back from dates to strings, you really do need the date formatter to specify the time zone, or else the string representation of a date will be in the device’s local timezone. This way, your formatter still works for both converting strings to dates, as well as back to strings.

Likewise, I’d suggest replacing the Z with either ZZZZZ or just X. Again, this is only critical if the date formatter is also being used to convert dates back to strings (otherwise, the resulting string will have +0000 rather than Z in it). Bottom line, I find using X/ZZZZZ means that I just never have to worry about it, it works when the formatter is converting 2019-09-30T09:10:32.537244Z to a Date object, or vice versa.

Thus:

let iso8601DateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSX"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()

func serverToLocal(string: String) -> Date? {
return iso8601DateFormatter.date(from: string)
}

func localToServer(date: Date) -> String {
return iso8601DateFormatter.string(from: date)
}

By the way, you talk about “server” date strings. Are you exchanging data via JSON? If you are parsing strings in JSON with JSONEncoder and JSONDecoder, you might use your formatter in the encoder's dateEncodingStrategy or the decoder's dateDecodingStrategy. That way, your underlying model objects can just be Date properties, and the JSON encoder/decoder will take care of converting the date strings in the JSON to Date objects (and back). And then you don’t need these serverToLocal and localToServer methods at all.


FWIW, for more information about quoting the T, setting the locale, etc., please see Apple’s Technical Q&A 1480. It’s old doc and is focused on Objective-C, but it talks about the concepts outlined here.

Converting UTC date format to local nsdate

Something along the following worked for me in Objective-C :

// create dateFormatter with UTC time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string

// change to a readable time format and change to local time zone
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];

I keep these two websites handy for converting different time formats:
http://www.w3.org/TR/NOTE-datetime

http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/

In Swift it will be:

// create dateFormatter with UTC time format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create date from string

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.local
let timeStamp = dateFormatter.string(from: date!)

Represent date string as UTC date and convert it into local timezone

The format specifier for 12 hour time is hh, not HH which is for 24 hour time.

Combining HH with an am/pm specifier a will give an incorrect result.

How to localize the hours in swift?

After days of searching, I found this answer Link

And find the write solution with this func:

private func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "HH:mm"

let tz = TimeZone.current
if tz.isDaylightSavingTime(for: Date()) {
// Summertime
let calendar = Calendar.current
if let summerDate = calendar.date(byAdding: .hour, value: 1, to: date) {
return dateFormatter.string(from: summerDate)
}else {
return dateFormatter.string(from: date)
}
}else {
return dateFormatter.string(from: date)
}
}
return nil
}


Related Topics



Leave a reply



Submit