NSDateFormatter does not work properly when converting from a Buddhist calendar to Gregorian calendar date formats

I am making an application that supports converting dates from the Buddhist calendar to the Gregorian (Note. The settings "General> International> Calendar" of the device on which I am testing are "Buddhists."). However, I cannot understand why NSDateFormatter does not parse my dates correctly. Here is my code:

NSDate *now = [NSDate date]; NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.calendar = gregorianCalendar; formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z"; NSString *formattedDate = [formatter stringFromDate:now]; NSDate *boomDate = [formatter dateFromString:formattedDate]; NSLog(@"now: %@, formattedDate (as string) > %@, boomDate (as date) > %@", now, formattedDate, boomDate); 

Xcode Magazine says:

 now: 2556-05-23 07:11:03 +0000, formattedDate (as string) > 2013-05-23 15:11:03 +0800, boomDate (as date) > 2556-05-23 07:11:03 +0000 

When I convert formattedDate (which is NSString) to NSDate, why does my NSDateFormatter parse it according to the format of the Buddhist calendar, even if I set it up correctly (especially formatter.calendar ). I need my formattedDate converted as an NSDate with a Gregorian calendar format. Based on my logic, I expect NSDateFormatter to give me a date with a Gregorian format, but that is not the case.

Basically, I need an NSDate after the Gregorian format from Buddhist NSDate.

Any ideas?

+1
source share
1 answer

NSDate is simply an object wrapper for a double value, indicating an offset from the NSDate date. It does not contain information about calendars or time zones. This is just a point in time.

What we, as people, decide to call this point in time, depends on our calendar and time zone. An NSDate is meaningless without a calendar and time zone.

When you print a date object using NSLog , the -description method on your date object is called, and the -description method formats the string using the locales of your device. This is why boomDate displayed with the calendar properties of a Buddhist; your Buddhist language uses the Buddhist calendar.

The variables now and boomDate are equal (try calling [now isEqualToDate:boomDate] ).

You can say that the conversion to gregorian succeeded because formattedDate shows the date as it would on a gregorian calendar.

+3
source

All Articles