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

自古美人都是妖i 提交于 2019-12-05 00:51:51

问题


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!


回答1:


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];



回答2:


The picked answer actually I can't compare them. only display is not enough for my project.

I finally come up with a solution that covert (NSDate) currentDate -> gregorianDate then we can compare those NSDates.

Just remember that the NSDates should be used temporary .(it do not attach with 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];


来源:https://stackoverflow.com/questions/6355405/how-to-get-todays-date-in-the-gregorian-format-when-phone-calendar-is-non-grego

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!