Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

current Date and Time - NSDate

I need to display the current Date and Time.

I have used ;

NSDate *currentDateNTime        = [NSDate date];

I want to have the current date and time (Should display the system time and not GMT time). The output should be in a NSDate format and not NSString.

for example;

    NSDate *currentDateNTime        = [NSDate date];
// Do the processing....

NSDate *nowDateAndTime = .....; // Output should be a NSDate and not a NSString
like image 589
Sharon Watinsan Avatar asked May 28 '12 16:05

Sharon Watinsan


3 Answers

Since all NSDate is GMT referred, you probably want this: (don'f forget that the nowDate won't be the actual current system date-time, but it's "shifted", so if you will generate NSString using NSDateFormatter, you will see a wrong date)

NSDate* currentDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* nowTimeZone = [NSTimeZone systemTimeZone];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:currentDate];
NSInteger nowGMTOffset = [nowTimeZone secondsFromGMTForDate:currentDate];

NSTimeInterval interval = nowGMTOffset - currentGMTOffset;
NSDate* nowDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
like image 50
Giorgio Marziani de Paolis Avatar answered Sep 24 '22 13:09

Giorgio Marziani de Paolis


Every moment in time is the same moment in time everywhere around the world —- it is just expressed as different clock times in different timezones. Therefore, you can't change the date to some other date that represents the time in your timezone; you must use an NSDateFormatter that you feed with the timezone you are in. The resulting string is the moment in time expressed in the clock time of your position.

Do all needed calculations in GMT, and just use a formatter for displaying.

like image 40
vikingosegundo Avatar answered Sep 26 '22 13:09

vikingosegundo


Worth reading Does [NSDate date] return the local date and time?

Some useful resources for anyone coming to this more recently:

Apple date and time programming guide do read it if you're doing anything serious with dates and times. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i?language=objc

Useful category on NSDate with lots of utilities does allow a ~new~ date to be generated based on an existing date. https://github.com/erica/NSDate-Extensions

There's also a swift version of the category https://github.com/erica/SwiftDates

like image 33
ReaddyEddy Avatar answered Sep 26 '22 13:09

ReaddyEddy