How to get local time on iOS [duplicate] - ios

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

Related

How to convert my server time to other country time?

I am getting time from server is 2016/07/19--12:20:00
Now I have to change this time according to country.
For example If I am in Auckland then time has to like 2016/07/19--18:50:00
I found so many solutions in stack overflow but I can't solve this.
Please help me
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY/MM/dd--HH:mm:ss"];
NSDate* sourceDate = [dateFormatter dateFromString:model.tripEndTime];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setDateFormat:#"YYYY/MM/dd--HH:mm:ss"];
NSString* localTime = [dateFormat stringFromDate:destinationDate];
NSLog(#"localTime:%#", localTime);
I tried with this code
Just convert the server time to UTC time, then convert to local country time. Just write a separate method for this
+(NSString*)convertLocaleTimeToChatTimeStampWithDateStr:(NSString *)strDate
{
NSDateFormatter *df = [DateHelper getDefaultTimeFormatter];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSDate *date = [df dateFromString:strDate];
[df setDateFormat:#"dd MMM, hh:mm a"];
[df setTimeZone:[NSTimeZone localTimeZone]];
return [df stringFromDate:date];
}
+(NSDateFormatter*)getDefaultTimeFormatter
{
NSDateFormatter *df = [NSDateFormatter new];
[df setDateStyle:NSDateFormatterNoStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
return df;
}
hope this will solve your problem. Thanks
It is better to use server timestamp. After getting timestamp convert it according to timezone

setting time when formatting date using NSDateformatter

I have following code to convert string to date. Is it possible that it sets time as "00:00:00" and not the current time?
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"yyyy-MM-dd"];
NSString *str = #"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];
This gives dt as "2014-08-08 15:20:00 +0000" because I did the operation at 15:20.
Edit: I am using this date to convert it to integer later to store it in database:
int t = [dt timeIntervalSince1970];
If you are displaying the date dt with NSLog you will see what the date description method provides. If you want to see the date in a specific way that suits you use NSDateFormatter to format the date.
Example:
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"yyyy-MM-dd"];
NSString *str = #"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];
NSDateFormatter *displayDateformat = [[NSDateFormatter alloc] init];
[displayDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *displayDateString = [displayDateformat stringFromDate:dt];
NSLog(#"displayDateString: %#", displayDateString);
Output:
2014-08-08
Note per Apple docs: "This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT."
A good practice is to use NSDateComponents
NSDate *yourDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:yourDate];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
// Set the time components manually
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
yourDate = [calendar dateFromComponents:dateComponents];
Update
iOS8 :
[[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];

How can i get local timezone in ios? [duplicate]

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)

Conversion of NSString to NSDate conversion - incorrect result

In short words I plan to get current dateTime, change the time and make it local to Malaysia Time by applying +0800 to timezone.
The result is unexpected :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd HH:mm:ss Z"];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *newDateString = [NSString stringWithFormat:#"%#",newDate];
NSString *maskString = [NSString stringWithFormat:#"%#", [newDateString substringToIndex:20]];
NSString *append = [maskString stringByAppendingString:#"+0800"];
NSLog(#"%#",append);
NSDate *finalLocalDate = [dateFormat dateFromString:append];
return finalLocalDate;
}
Results :
for NSLog Append : 2013-12-07 23:59:17 +0800
but finalLocalDate : 2013-01-07 15:59:17 +0000
Found the answer with much shorter solution, so I posted here in case it helps anyone in future.
for returning, the problem was different time zones so by adding this line of
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
we set the timezone to system time zone then we remove unnecessary codes :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSLog(#"%#",newDate);
return newDate;
}
Correct Result : 2013-12-08 07:59:17 +0000
try this:
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
NSDate *malaysianTime = [NSDate dateWithTimeIntervalSince1970:now+(8*60*60)]; //8h in seconds
If your computer is running in the correct timezone don't set a timezone.
Create your newDate value and then --
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSString* printableDate = [fmt stringFromDate:newDate];
NSLog(#"The date is %#", printableDate);
Only set a timezone (in both NSCalendar and NSDateFormatter) if the desired timezone is not the one your computer/phone is currently using.
Note that if you NSLog newDate directly it will print in GMT timezone. This is the way it's supposed to be -- you always use NSDateFormatter for a printable date. When you NSLog an NSDate directly you get GMT, by design.

Date and Time issue in ios [duplicate]

This question already has answers here:
NSDate is not returning my local Time zone /default time zone of device
(7 answers)
Closed 9 years ago.
I am using the datepicker for picking the time but after sending to the server when I am retrieving back then its showing 5-6 hour difference.
Server hosted in USA.
So how I will do it accurately without any difference, User do request from any where.
Thanks,
Arun
UTC is standard time zone to be used. Following is the code to get date in UTC
+(NSString *)getCurrentTime{
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-ddHH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *dateStr = [dateFormat stringFromDate:date];
RELEASE_OBJECT(date)
RELEASE_OBJECT(dateFormat)
return dateStr;
}
Send the date with the timezone. For example:
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [formatter dateFromString:dateString];
Will include the timezone and the server will be able to translate to its own timezone.
We use the ISO 8601 for better compatibility. There are also NSFormatter subclasses that to convert from ISO 8601 to NSDate and back (like this).
It is time zone issue. You can use [yourDate dateByAddingInterval:[NSTimeZone secondsFromGMT]]; .
Please try to set the Locale for the time:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MM yyyy hh:mm:ss"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease]];
NSDate* sourceDate = [dateFormatter dateFromString:dateString];
//Timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//Interval in Timezones
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//converted date
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSString *strFinalDate = [dateFormatter stringFromDate:destinationDate];
[dateFormatter release];
[destinationDate release];
If you are sending your iPhone default times to server and server is also sending the same time which you have send it then it will be problem of the converting your NSDate to NSString with NSDateFormatter with some different timezone.
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
Use above code when you using NSDateFormatter.

Resources