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

NSDate *now = [[NSDate alloc] init]; 

indicates the current date.

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

Now the question is how to convert to a Gregorian date or make sure that it will be in Gregorian format from the very beginning. This is important for some messages on the server.

Thanks!

+4
source share
2 answers

NSDate is simply a point in time and in itself has no format.

Format NSDate, for example. string, you must use NSDateFormatter. It has a calendar property, and if you set this property to an instance of the Gregorian calendar, the displayed format will correspond to the 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]; 
+14
source

The selected answer, in fact, I can not compare them. for my project, display is not enough.

Finally, I came up with a solution that hides (NSDate) currentDate -> gregorianDate then we can compare these NSDates.

Just remember that NSDates should be used temporarily (it is not attached by any calendar)

  NSDate* currentDate = [NSDate date]; NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *gregorianComponents = [gregorianCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:[gregorianComponents day]]; [comps setMonth:[gregorianComponents month]]; [comps setYear:[gregorianComponents year]]; [comps setHour:[gregorianComponents hour]]; [comps setMinute:[gregorianComponents minute]]; [comps setSecond:[gregorianComponents second]]; NSCalendar *currentCalendar = [NSCalendar autoupdatingCurrentCalendar]; NSDate *today = [currentCalendar dateFromComponents:comps]; 
+1
source

All Articles