Following is the code I am writing to convert UTC time to local time :
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter1 setLocale:locale];
NSDate *date = [dateFormatter1 dateFromString:dateString];
dateString = [date descriptionWithLocale:[NSLocale systemLocale]];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"HH:mm"];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateString = [dateFormatters stringFromDate: destinationDate];
But this way I am getting a difference of 1 hour. i.e. if date displayed on web app is 12:30, on the app it is displayed as 13:30. Why is that so ?
Try with this code:
- (NSDate *) UTCTimeToLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: yourDate];
return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}
- (NSDate *) LocalTimeToUTCTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = -[tz secondsFromGMTForDate: yourDate];
return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}
You need to learn and accept the principles of handling times and dates.
NSDate represents points in time, independent of any time zone. If we are talking on the phone, and our computers calculate [NSDate date], they get the exact same date, even if our watches display totally different times.
Calendars with time zone information transform between NSDate and something that a user in one particular part of the world expects. So the same NSDate is converted to a string to match what your watch displays, or what my watch displays, which would be different. There should be no need to modify an NSDate in any of this, as you did.
Related
I know this is a very question and asked multiple times before.But this is something i get stuck every time.
Now, i want to convert a date string from web service which is in Argentina local zone(UTC-3:0) and want to convert this that to device local time zone(Suppose UTC+5:30). Here is my code
-(NSDate *)getLocaDateStringFromDate:(NSString *)sourceDate andSourceTime:(NSString *)sourceTime
{
//sourceDate is #"2015-10-16"; and sourceTime is #"00:00:00"
static NSDateFormatter* df = nil;
if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = #"yyyy-MM-dd HH:mm:ss";
}
NSString* source = [sourceDate stringByAppendingString:[NSString stringWithFormat:#" %#", sourceTime]];
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:#"ART"];
[df setTimeZone: sourceZone];
NSDate *ds = [df dateFromString:source];
NSLog(#"sourceZone time is %#" , [df stringFromDate: ds]);//sourceZone time is 2015-10-16 00:00:00, correct!
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(#"local time is %#" , [df stringFromDate: ds]);//local time is 2015-10-16 08:30:00,, correct
NSString* str = [df stringFromDate: ds];
return [df dateFromString:str]; //this return 2015-10-16 03:00:00 +0000, why?
}
My question is that why my method return date in UTC, regardless of my time zone set to systemTimeZone. I get correct string but date is incorrect.
Any help would be appreciated.
1.) First, create an NSDateFormatter to get the NSDate sent from the server.
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
2.) Convert the date string to a NSDate.
NSDate* sourceDate = [dateFormatter dateFromString:dateString];
3) Specify ,Local and Destination timezone in which you want to convert your date.
For getting timezone of your source date:
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
For getting User timezone :
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
4.) Calculate the inverval between source timezone and user timezone as given bellow:
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
5.) Now, create an NSDateFormatter for formatting date in which you want to show.
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setDateFormat:#"M/d/yy 'at' h:mma"];
NSString* localTime = [dateFormat stringFromDate:destinationDate];
NSLog(#"localTime:%#", localTime);
Hope it is useful for you :)
This question already has answers here:
Get current iPhone device timezone date and time from UTC-5 timezone date and time iPhone app?
(3 answers)
Closed 8 years ago.
I need to set local timezones as per the location of the ios device.
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
or
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"GTC+5.30"]];
is suited?
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(#"User's current time in their preference format:%#",currentTime);
You can get the name of the local time zone using:
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
This is how I do it:
NSString *strDateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSS";
// ---------------------------------------------------------
// input date is UTC date time, need to convert that time
// to user's own local device timezone to get correct date
// ---------------------------------------------------------
NSDateFormatter *dateFormatterUTC = [[NSDateFormatter alloc] init];
[dateFormatterUTC setDateFormat:strDateFormat];
[dateFormatterUTC setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// get UTC Date first
NSDate* utcDate = [dateFormatterUTC dateFromString:strDate];
// get local date from UTC Date
NSDateFormatter *dateFormatterLocal = [[NSDateFormatter alloc] init];
[dateFormatterLocal setDateFormat:strDateFormat];
[dateFormatterLocal setTimeZone:[NSTimeZone systemTimeZone]];
// get final local date calculated by offsetting UTC Date
NSDate *localDate = [dateFormatterUTC dateFromString:[dateFormatterLocal stringFromDate:utcDate]];
NSDate *localNowDate = [dateFormatterUTC dateFromString:[dateFormatterLocal stringFromDate:[NSDate date]]];
NSString *dateStr = #"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(#"date : %#",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] autorelease];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(#"DateString : %#", dateStr);
- (Courtesy: Yuvaraj.M)
You can use the localTimeZone class method of NSTimeZone class to get a relative time zone object that decodes itself to become the default time zone for any locale in which it finds itself.
SRC: https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSTimeZone_Class/Reference/Reference.html#//apple_ref/occ/clm/NSTimeZone/localTimeZone
If you need latitude and longitude: Get the official time zone database at http://www.iana.org/time-zones. Download tzdata2013g.tar.gz. There's a file in that archive named zone.tab that gives a lat/long for each time zone, for example:
CH +4723+00832 Europe/Zurich
The +4723+00832 indicates latitude = +47º23", longitude = +8º23"
(SRC:Get Timezone/country from iPhone)
I am trying to find the time difference between 2 dates. but i am getting values as -0.0000, nan, or -357683564. below is my code to find time difference. am i doing any wrong in this calculations ?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateFormat = #"YYYY-MM-dd HH:MM:SS ±HHMM";//MM/dd/yyyy
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[formatter setLocale:usLocale];
NSDate *intialTime= [formatter dateFromString:[NSString stringWithFormat:#"%#",[dateArray objectAtIndex:i]]];//[formatter dateFromString:#"12/11/2005"];
NSDate *presentDate = [NSDate date];
NSTimeInterval timeInterval = [presentDate timeIntervalSinceDate:intialTime];
int seconds = (int)ceil(timeInterval);
int mins = seconds / 60;
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = timeInterval / secondsInAnHour;
NSLog(#"Time interval in Mins:%d -- %.4f -- %d",mins,timeInterval,hoursBetweenDates);
In Log :
Time interval in Mins:-35791394 -- nan -- -2147483648
intialTime - (null) and presentDate - 2014-05-09 10:30:15 +0000
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
NSDate *dateToday = [NSDate date];
NSString *date = #"09-05-14"; // Put your initial date here...
[df setDateFormat:#"HH:mm:ss"];
NSString *todayString = [df stringFromDate:[NSDate date]];
NSString *todaysDateTime = [date stringByAppendingString:todayString];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *initialDate = [df dateFromString:todaysDateTime];
NSTimeInterval ti = [initialDate timeIntervalSinceDate:dateToday];
I fixed my Issue by using NSTimeZone. here was my problem.it was displaying date as their server date and my current date was not matching to timezone and not able to format it. Thanks for you all friends for helping me to find my mistake.
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:gmt];
How can I convert date with timezone1 to date with device local timezone2?
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"Asia/Jerusalem"]];
NSDate *date = [dateFormat dateFromString:timestamp];
then something like:
[dateFormat2 setTimeZone:[NSTimeZone localTimeZone]];
date2 = [dateFormat2 dateFromDate:date withOtherTimeZone:zone];
UPDATE:
I think I got it.
//get source date from the server
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSDate *sourceDate = [dateFormat dateFromString:timestamp];
//set timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:#"Asia/Jerusalem"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//calc time difference
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//set current real date
NSDate* date = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
Is it ok?
OK first off, time is time. At this very second, everywhere on earth, its is the same second. Stop thinking of time format as time. It's not. All time should be in GMT, and then you can display it based on TimeZone.
Date *d = [NSDate date] ;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
NSTimeZone *nyTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"sometimeabbr."];
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimezone: nyTimeZone];
NSLog(#"ny time is %#" , [df stringFromDate: d]);
[df setTimeZone: localTimeZone];
NSLog(#"local time is %#" , [df stringFromDate: d]);
If you are given a string date and need to convert, create NSDateFormatter to ingest the string date. Make sure you set a timezone. Now you have a NSDate object (no timezone in NSDates), that yiou can format into any other timezone you want.
Please for the love all all that is holy. Treat time as seconds that marches forward, and timezones as the formatting of those timezones.
This is the answer:
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:#"Asia/Jerusalem"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//calc time difference
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//set current real date
NSDate* date = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
*Different time zone date convert to local time zone date in swift.
let timeZone1 = NSTimeZone(name: timeZone1Name)
let localTimeZone = NSTimeZone.localTimeZone()
let timeZone1Interval = timeZone1?.secondsFromGMTForDate(timezone1Date!)
let deviceTimeZoneInterval = localTimeZone.secondsFromGMTForDate(timezone1Date!)
let timeInterval = Double(timeZone1Interval! - deviceTimeZoneInterval)
let originalDate = NSDate(timeInterval: timeInterval, sinceDate: timezone1Date!)
let dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd HH:mm:ss Z"
NSLog("Converted date: \(dateFormater.stringFromDate(originalDate))")
let dateString = dateFormater.stringFromDate(originalDate)
let localTimeZoneDate = dateFormater.dateFromString(dateString)
*
This question already has answers here:
Retrieving current local time on iPhone?
(7 answers)
Closed 9 years ago.
I just noticed that NSDate *nowDate = [NSDate date]; gives me GMT+0 Time and not the local time. So basically on my iPad it's 13:00 and the output of this code is 12:00.
How do I get local time properly?
Give it a Shot !
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];//use `[NSTimeZone localTimeZone]` if your users will be changing time-zones.
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
It will give you the time according to the current system timezone.
NSDate does not care about timezones. It simply records a moment in time.
You should set the local timezone when using the NSDateFormatter to get a string representation of the date:
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // Set date and time styles
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateString = [dateFormatter stringFromDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
NSDate *d = [calendar dateFromComponents:dateComponents];
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(#"%#",currentTime);