How to get today's date in the Gregorian format when phone calendar is non-Gregorian?

Vanja picture Vanja · Jun 15, 2011 · Viewed 9k times · Source
NSDate *now = [[NSDate alloc] init];  

gives the current date.

However if the phone calendar is not Gregorian (on the emulator there is also Japanese and Buddhist), the current date will not be Gregorian.

The question now is how to convert to a Gregorian date or make sure it will be in the Gregorian format from the beginning. This is crucial for some server communication.

Thank you!

Answer

Morten Fast picture Morten Fast · Jun 15, 2011

NSDate just represents a point in time and has no format in itself.

To format an NSDate to e.g. a string, you should use NSDateFormatter. It has a calendar property, and if you set this property to an instance of a Gregorian calendar, the outputted format will match a Gregorian style.

NSDate *now = [NSDate date];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:gregorianCalendar];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];

NSString *formattedDate = [formatter stringFromDate:now];

NSLog(@"%@", formattedDate);

[gregorianCalendar release];
[formatter release];