Convert date from timezone to device local timezone and date - ios

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)
*

Related

Getting one hour difference on date

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.

iOS convert date to local time zone?

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 :)

Convert an NSDate to local timezone, check if 'today' or 'tomorrow' and get the date in NSString

I know similar questions have been asked before, but my situation is slightly different and I've been trying to get a solution for it.
I have my code doing so:
NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:time / 1000];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:messageDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:messageDate];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
// get final date in LocalTimeZone
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:messageDate];
static NSDateFormatter *formatter;
static dispatch_once_t sOnce = 0;
dispatch_once(&sOnce, ^{
formatter = [[NSDateFormatter alloc] init];
});
[formatter setDateFormat:format];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *absTime = [formatter stringFromDate:destinationDate];
Now I have a problem here. Eg:
time = 1432028287411
messageDate = 2015-05-19 09:38:07 +0000
(NSInteger) currentGMTOffset = -25200
(NSInteger) gmtOffset = 0
destinationDate = 2015-05-19 02:38:07 +0000
absTime = Mon, May 18
As you can see, the NSString is not consistent with the date that I'm explicitly converting to local timezone. This is also causing problems when I use 'isDateInToday' method. What am I missing here? Note: My local time zone is set to PST.
I am posting this is Swift, but since the problem is about correct usage of the API rather than Objective-C, this will hopefully serve the same role as pseudo code and will be useful for you. Basically, you are converting the time twice, once by subtracting the interval and once by specifying TZ in the formatter.
Convert to NSDate
let time:NSTimeInterval = 1432028287411/1000
let date = NSDate(timeIntervalSince1970: time)
Formatter to display the result in UTC/GMT
let utcFormatter = NSDateFormatter()
utcFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
utcFormatter.dateFormat = "hh:mm:ss zzz"
Formatter to display the result in current time zone, i.e. PDT
let currentTzFormatter = NSDateFormatter()
currentTzFormatter.timeZone = NSTimeZone.defaultTimeZone()
currentTzFormatter.dateFormat = "hh:mm:ss zzz"
Show GMT/UTC time
utcFormatter.stringFromDate(date)
Show PDT (local TZ) time
currentTzFormatter.stringFromDate(date)
Check if the date is today (in local TZ)
let calendar = NSCalendar.currentCalendar()
calendar.isDateInToday(date) <- will show false today, because it is 26th today, not 19th, but will work correctly with today's date.
The only thing wrong with your code is the time zone. Here is a rough outline of how it should look:
NSString *dateString = #"2011-09-02 17:49:54";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *tz = [NSTimeZone localTimeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:tz];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
NSLog(#"%#", [date descriptionWithCalendarFormat:nil timeZone:tz locale:nil]);

How to get current local time in ios

I'm try to get local time from device
nsdate will return the UTC time
when I convert with localtime zone the string will return current local time...
again I try to convert string to local date but it will return only UTC time
This is my code... how can I get Local time in NSDate...
NSDate *currentDate = [NSDate date];
NSLog(#"currentDate: %#", currentDate); // Result: currentDate: 2014-05-19 05:21:50 +0000
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter2 setDateFormat:#"yyyy/MM/dd HH:mm:ss"];
NSString *strDate = [dateFormatter2 stringFromDate:currentDate];
NSLog(#"strDate: %#", strDate); // Result: strDate: 2014/05/19 10:51:50
NSDate *newDate = [dateFormatter2 dateFromString:strDate];
NSLog(#"newDate: %#", newDate); // Result: newDate: 2014-05-19 05:21:50 +0000
can any one help to get local datetime in NSDate
Try this:
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
The time is always saved in NSDate as UTC, that can not be changed.
One can get a string representation for the local timezone, the OP has done that.
NSDate has a reference date of "the first instance of 1 January 2001, GMT"

formatting NSDate object changes the time zone

I get the current NSDate in the user time zone with the following code
-(NSDate *)getCurrentDateinLocalTimeZone
{
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
return [dateFormatter dateFromString: [dateFormatter stringFromDate:destinationDate]];
}
and at some other point in my app i want to format the date as "HH:mm" for UI purposes so i use the following method
-(NSString *)formatDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"HH:mm";
return [dateFormatter stringFromDate:date];
}
if the output of the second method is shifted by 3 hours from the result of the 1st method ,,, i only want to change the format of NSDate not the time , what am i doing wrong ?
The getCurrentDateinLocalTimeZone method adjusts the date for the time zone, formats it using a format string that chops off the time zone, and parses the formatted string back. The resulting NSDate is in the UTC time zone (the +0000 in 2012-07-15 16:28:23 +0000 indicates UTC time). The formatDate: method uses dateFormatter that is set up for the local time zone, producing a different time. You should set the formatter to use UTC to get the correct time: replace
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
with
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
in the formatDate: method.

Resources