Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - current date considering daylight saving

Tags:

iphone

My country is located in GMT+0. We are +1 hour now, because we are in daylight saving.

When I do

[NSDate date];

it was supposed to return the current date and time, but when I do that, I receive the GMT time not considering the daylight saving.

This is what the docs say about the date command

Creates and returns a new date set to the current date and time.

Why Apple does that to us? Why everything is so complex? Is this a bug? Is there a way to get the current real time the device is on? the same time that is displayed on the device's clock?

My app depends on dates and times and having a wrong date for an user located in a different timezone around the world that is on summertime or wintertime will be a disaster.

Thanks.


EDIT

After several answers, I have tried this code:

NSDate *wrongToday = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter wrongToday];

NSDate *today = [dateFormatter dateFromString:currentTime];

guess what, today = wrongToday... in other words, no change, I continue to have the wrong date without daylight saving. what is more amazing is that currentTime shows in NSString the date with daylight saving...

any clues? thanks again.

like image 237
Duck Avatar asked Jul 28 '11 22:07

Duck


2 Answers

albertamg, MRAB and Joe Osborn are all correct. They're all trying to explain to you that NSDate is a "number", "an absolute moment in time".

This value is INDEPENDENT of whether you're in London, in Los Angeles or in Singapore. It's independent of whether your county respects daylight savings time.

To INTERPRET NSDate in terms of something recognizable (like "Th July 28, 4:28pm"), you need an NSDateFormatter. You also need to make sure your locale is defined correctly: including timezone, whether daylight savings is honored, and various time/date formatting conventions.

'Hope that helps ..

like image 58
paulsm4 Avatar answered Sep 20 '22 15:09

paulsm4


Hard coding:

    BOOL isDayLightSavingTime = [sysTimezone isDaylightSavingTimeForDate:currentDate];
if (isDayLightSavingTime) {
    NSTimeInterval timeInterval = [sysTimezone  daylightSavingTimeOffsetForDate:currentDate];
    currentDate = [currentDate dateByAddingTimeInterval:timeInterval];
}

the current date is now daylight saving time.

Hope help.

like image 30
frank Avatar answered Sep 20 '22 15:09

frank