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!)
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!!
Convert UTC to local time with NSDateFormatter
The question doesn't specify the nature of what you mean by converting, exactly, but the first thing you should do, regardless of the final goal, is to correctly parse the server response using a properly configured NSDateFormatter
. This requires specification of the correct format string, and the time zone must be explicitly set on the formatter or it will infer it from the local time, which would be incorrect in most cases.
Specify The Format String
Let's look at the input string provided:
20140621-061250
This uses four digits for the year, two digits (with a zero-padding) for the month, and two digits (presumably, these will be zero-padded as well) for the day. This is followed by a -
, then two digits to represent the hour, 2 digits for the minute, and 2 digits for the second.
Referring to the Unicode date format standards, we can derive the format string in the following way. The four digits representing the calendar year will be replaced with yyyy
in the format string. Use MM
for the month, and dd
for the day. Next would come the literal -
. For the hours, I assume that it will be in 24 hour format as otherwise this response is ambiguous, so we use HH
. Minutes are then mm
and seconds ss
. Concatenating the format specifiers yields the following format string, which we will use in the next step:
yyyyMMdd-HHmmss
In our program, this would look like:
NSString *dateFormat = @"yyyyMMdd-HHmmss";
Configure the input date formatter
The time format above does not specify a time zone, but because you have been provided the specification for the server response that it represents the UTC time, we can code this into our application. So, we instantiate an NSDateFormatter
, set the correct time zone, and set the date format:
NSTimeZone *inputTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setTimeZone:inputTimeZone];
[inputDateFormatter setDateFormat:dateFormat];
Convert the input string to an NSDate
For demonstration purposes, we hard-code the string you received from the server response; you would replace this definition of inputString
with the one you get from the server:
NSString *inputString = @"20140621-061250";
NSDate *date = [inputDateFormatter dateFromString:inputString];
At this point, we have the necessary object to do any further conversions or calculations - an NSDate
which represents the time communicated by the server. Remember, an NSDate
is just a time stamp - it has no relation to a time zone whatsoever, which only plays a role when converting to and from string representations of the date, or representations of a calendrical date via NSDateComponents
.
Next steps
The question doesn't clearly specify what type of conversion is needed, so we'll see an example of formatting the date to display in the same format as the server response (although, I can't think of a likely use case for this particular bit of code, to be honest). The steps are quite similar - we specify a format string, a time zone, configure a date formatter, and then generate a string (in the specified format) from the date:
NSTimeZone *outputTimeZone = [NSTimeZone localTimeZone];
NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
[outputDateFormatter setTimeZone:outputTimeZone];
[outputDateFormatter setDateFormat:dateFormat];
NSString *outputString = [outputDateFormatter stringFromDate:date];
Since I'm in UTC-06:00, printing outputString
gives the following:
20140621-001250
It's likely you'll instead want to use setDateStyle:
and setTimeStyle:
instead of a format string if you're displaying this date to the user, or use an NSCalendar
to get an NSDateComponents
instance to do arithmetic or calculations on the date. An example for displaying a verbose date string to the user:
NSTimeZone *outputTimeZone = [NSTimeZone localTimeZone];
NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
[outputDateFormatter setTimeZone:outputTimeZone];
[outputDateFormatter setDateStyle:NSDateFormatterFullStyle];
[outputDateFormatter setTimeStyle:NSDateFormatterFullStyle];
NSString *outputString = [outputDateFormatter stringFromDate:date];
Printing outputString
here gives us the following:
Saturday, June 21, 2014 at 12:12:50 AM Mountain Daylight Time
Note that setting the time zone appropriately will handle transitions over daylight savings time. Changing the input string to "20141121-061250" with the formatter style code above gives us the following date to display (Note that Mountain Standard Time is UTC-7):
Thursday, November 20, 2014 at 11:12:50 PM Mountain Standard Time
Summary
Any time you get date input in a string form representing a calendar date and time, your first step is to convert it using an NSDateFormatter
configured for the input's format, time zone, and possibly locale and calendar, depending on the source of the input and your requirements. This will yield an NSDate
which is an unambiguous representation of a moment in time. Following the creation of that NSDate
, one can format it, style it, or convert it to date components as needed for your application requirements.
How to convert a string UTC date to NSDate in Swift
I think this should work
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.date(from: date)
How to convert UTC date string to local time (systemTimeZone)
This should do what you need:
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"LLL d, yyyy - HH:mm:ss zzz";
NSDate *utc = [fmt dateFromString:@"June 14, 2012 - 01:00:00 UTC"];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(@"%@", local);
Note that your example is incorrect: when it's 1 AM on June-14th in UTC, it's still June-13th in EST, 8 PM standard or 9 PM daylight savings time. On my system this program prints
Jun 13, 2012 - 21:00:00 EDT
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)
}
Related Topics
Coredata Get Distinct Values of Attribute
Format Uilabel with Bullet Points
Storing Authentication Tokens on iOS - Nsuserdefaults VS Keychain
How to Set the Uinavigationbar with Gradient Color
Facebook Sdk: App Not Registered as a Url Scheme
Get the Current View Controller from the App Delegate
What Are the Benefits of Using Storyboards Instead of Xib Files in iOS Programming
Find an Item and Change Value in Custom Object Array - Swift
Dynamic Size Uicollectionview Cell
Detect If App Is Running in Slide Over or Split View Mode in iOS 9
Query Available iOS Disk Space with Swift
What Is the Bundle Identifier of Apple's Default Applications in iOS
Error Itms-90164/90046: Invalid Code Signing Entitlements
Nsdateformatter: Date According to Currentlocale, Without Year