How do I convert a UTC NSDate
to local timezone NSDate in Objective C or/and Swift?
-
14Dates certainly do have time zones.– Glenn MaynardDec 3, 2012 at 17:41
-
1If it helps, think of temperatures. They can be expressed in Fahrenheit, Celsius, or Kelvin. But the information being expressed (the average movement of the molecules) has no intrinsic unit, although it is only meaningful to us when expressed in some unit.– software evolvedJan 15, 2013 at 4:13
-
7@DaveDeLong NSDate does have a timezone. From the NSDate class reference: "This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT." Note the clear and specific reference to GMT.– Murray SagalMar 20, 2013 at 8:13
-
3I disagree. NSDate does NOT have a timezone. To specify the timezone for the NSDate, you use an NSCalendar object or an NSDateFormatter object. If you create an NSDate from a string that has no timezone specified, then the NSDate will assume that the string is in GMT time.– RicksterDec 3, 2013 at 2:04
-
3@Murray I believe you are mistaken. Just because NSDates are relative to a reference date that the Apple docs format for us in GMT, does not mean NSDates intrinsically have timezones, other than perhaps a default way of interpreting times when no timezone is specified. The documentation could have just as easily said the absolute reference date was 1 Jan 2001 02:00 Budapest time. They are thereby just as much anchored to any timezone as GMT. See this answer stackoverflow.com/a/8866731/558352– Bradley ThomasSep 5, 2016 at 20:36
15 Answers
NSTimeInterval seconds; // assume this exists
NSDate* ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
NSString* ts_local_string = [df_local stringFromDate:ts_utc];
// you can also use NSDateFormatter dateFromString to go the opposite way
Table of formatting string parameters:
https://waracle.com/iphone-nsdateformatter-date-formatting-table/
If performance is a priority, you may want to consider using strftime
-
probably worth mentioning you can use formatter to read dates back in from strings as well– slfSep 8, 2011 at 18:41
-
34@DaveDeLong that's all well and good if you're just displaying the date as a string. But there are perfectly valid reasons for doing time zone conversions on a date. For example, if you want to default the date on a UIDatePicker using setDate:. Dates returned by web services often are UTC, but represent an event in the user's local time zone, like a TV listing. Passing in an unconverted date will display the incorrect time in the picker. Oct 16, 2011 at 4:31
-
5@GlennMaynard I disagree. The essence of this answer is that no conversion to the
NSDate
object is necessary, which is correct. Conversion to a timezone happens when the date is formatted, not when it is created, because dates don't have timezones. Jul 19, 2012 at 21:21 -
1
-
1
EDIT When i wrote this I didn't know I should use a dateformatter which is probably a better approach, so check out slf
's answer too.
I have a webservice that returns dates in UTC. I use toLocalTime
to convert it to local time and toGlobalTime
to convert back if needed.
This is where I got my answer from:
https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/
@implementation NSDate(Utils)
-(NSDate *) toLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: self];
return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}
-(NSDate *) toGlobalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = -[tz secondsFromGMTForDate: self];
return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}
@end
-
28Don't do this. NSDates are always in UTC. This just confuses the issue.– JeremyPAug 31, 2012 at 9:49
-
13This can be very useful for the "webservice" case noted above. Let's say you have a server that stores events in UTC and the client wants to ask for all events that happened today. To do this, the client needs to get the current date (UTC/GMT) and then shift it by its timezone offset before sending it to the server. Oct 1, 2012 at 10:57
-
@JeremyP It would be more accurate to say that NSDates are always in GMT. From the NSDate class reference: "This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT." Note the clear and specific reference to GMT. There is a technical difference between GMT and UTC but that is mostly irrelevant to the solutions most people are looking for. Mar 20, 2013 at 8:16
-
3Would be nice to note where you copied the code from: agilewarrior.wordpress.com/2012/06/27/…– aryaxtMar 25, 2015 at 18:24
-
2@aryaxt you are right, i'm sorry. I honestly didn't remember where I copied from when I posted the answer. Mar 26, 2015 at 7:41
The easiest method I've found is this:
NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
-
3This answer feels more portable. The answer below assumes the timezone is fixed at runtime whereas the answer above derives the timezone from the platform. Jul 7, 2014 at 5:54
-
10Very helpful. One addition,
secondsFromGMTForDate
should be used if you want to account for daylight saving. See Apple Docs Dec 15, 2014 at 2:33 -
1
Swift 3+: UTC to Local and Local to UTC
extension Date {
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
If you want local Date and time. Try this code:-
NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
-
Great answer! This will grab the current date. An adaptation of this which uses a date string would be to replace
[NSDate date]
with[NSDate dateWithNaturalLanguageString:sMyDateString]
.– VolomikeJan 20, 2016 at 19:29
Convert your UTC date to Local Date
-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
{
NSDateFormatter *dtFormat = [[NSDateFormatter alloc] init];
[dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *aDate = [dtFormat dateFromString:strDate];
[dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone systemTimeZone]];
return [dtFormat stringFromDate:aDate];
}
Use Like This
NSString *localDate = [self getLocalDateTimeFromUTC:@"yourUTCDate"];
-
1
Here input is a string currentUTCTime (in format 08/30/2012 11:11) converts input time in GMT to system set zone time
//UTC time
NSDateFormatter *utcDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[utcDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[utcDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: 0]];
// utc format
NSDate *dateInUTC = [utcDateFormatter dateFromString: currentUTCTime];
// offset second
NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT];
// format it and send
NSDateFormatter *localDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[localDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[localDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]];
// formatted string
NSString *localDate = [localDateFormatter stringFromDate: dateInUTC];
return localDate;
//This is basic way to get time of any GMT time.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"]; // 09:30 AM
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // For GMT+1
NSString *time = [formatter stringFromDate:[NSDate date]]; // Current time
Convert the date from the UTC calendar to one with the appropriate local NSTimeZone.
I write this Method to convert date time to our LocalTimeZone
-Here (NSString *)TimeZone parameter is a server timezone
-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
[serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *theDate = [serverFormatter dateFromString:defaultTime];
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
return dateConverted;
}
Since no one seemed to be using NSDateComponents
, I thought I would pitch one in...
In this version, no NSDateFormatter
is used, hence no string parsing, and NSDate
is not used to represent time outside of GMT (UTC). The original NSDate
is in the variable i_date
.
NSCalendar *anotherCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:i_anotherCalendar];
anotherCalendar.timeZone = [NSTimeZone timeZoneWithName:i_anotherTimeZone];
NSDateComponents *anotherComponents = [anotherCalendar components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitNanosecond) fromDate:i_date];
// The following is just for checking
anotherComponents.calendar = anotherCalendar; // anotherComponents.date is nil without this
NSDate *anotherDate = anotherComponents.date;
i_anotherCalendar
could be NSCalendarIdentifierGregorian
or any other calendar.
The NSString
allowed for i_anotherTimeZone
can be acquired with [NSTimeZone knownTimeZoneNames]
, but anotherCalendar.timeZone
could be [NSTimeZone defaultTimeZone]
or [NSTimeZone localTimeZone]
or [NSTimeZone systemTimeZone]
altogether.
It is actually anotherComponents
holding the time in the new time zone. You'll notice anotherDate
is equal to i_date
, because it holds time in GMT (UTC).
You can try this one:
NSDate *currentDate = [[NSDate alloc] init];
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"ZZZ"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSMutableString *mu = [NSMutableString stringWithString:localDateString];
[mu insertString:@":" atIndex:3];
NSString *strTimeZone = [NSString stringWithFormat:@"(GMT%@)%@",mu,timeZone.name];
NSLog(@"%@",strTimeZone);
Please use this code.
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
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];
Solution for SwiftDate library:
// Take date by seconds in UTC time zone
var viewModelDate: Date = DateInRegion(seconds: Double(backendModel.scheduledTimestamp)).date
...
// Convert date to local timezone and convert to string by format rule.
label.text = viewModelDate.convertTo(region: .current).toFormat(" EEE MM/dd j:mm")
Convert UTC time to current time zone.
call function
NSLocale *locale = [NSLocale autoupdatingCurrentLocale];
NSString *myLanguageCode = [locale objectForKey: NSLocaleLanguageCode];
NSString *myCountryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *rfc3339DateTimeString = @"2015-02-15 00:00:00"];
NSDate *myDateTime = (NSDate*)[_myCommonFunctions _ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:myLanguageCode CountryCode:myCountryCode Formated:NO];
Function
-NSObject*)_ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:(NSString *)lgc CountryCode:(NSString *)ctc Formated:(BOOL) formated
{
NSDateFormatter *sUserVisibleDateFormatter = nil;
NSDateFormatter *sRFC3339DateFormatter = nil;
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
if (sRFC3339DateFormatter == nil)
{
sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *myPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSString stringWithFormat:@"%@", timeZone]];
[sRFC3339DateFormatter setLocale:myPOSIXLocale];
[sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];
if (formated == YES)
{
NSString *userVisibleDateTimeString;
if (date != nil)
{
if (sUserVisibleDateFormatter == nil)
{
sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];
[sUserVisibleDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
}
// Convert the date object to a user-visible date string.
userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];
return (NSObject*)userVisibleDateTimeString;
}
}
return (NSObject*)date;
}