Converting NSDate from a calendar to another

2019-05-28 01:06发布

问题:

I'm having trouble here. Took me hours but no use. Please keep in mind I checked the heck of StackOverFlow for a fix but there isn't any.

When I convert the _date Object from Gregorian to Hijri it does not convert. I know that because when I print it it still gives me the Gregorian day. This troubles me because I want to setDate of a UIDatePicker and it's setting it incorrectly because the _date is gregorian and my UIDatePicker object calendar set to setCalendar:_hijriCalendar

//DATE SETTING
_date = [NSDate date];
_hijriCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSIslamicCalendar];
_gregCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

unsigned units = NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *currentDateComponents = [_hijriCalendar components:units fromDate:[NSDate date]];


NSDate *islamicDate =[_hijriCalendar dateFromComponents:currentDateComponents];

NSLog(@" Current Date: %@",islamicDate);  //this outputs gregorian current date not Hijri

NOTE: Guys, I don't want just print the date. I know using a NSDateFotmatter set to the correct NSCalendar object will do the job. But I want to convert the date to a new date to set it to my UIDatePicker. I hope you guys get what I mean.

回答1:

An NSDate object represents a moment in time, irrespective of any calendar, time zone, or relativity (this last one is generally considered to be a non-issue in Earth-based computer science.)

When you create an instance of NSDate through any means, it is stored as simply the number of seconds since a fixed point in time (12:00 AM GMT on January 1, 2001 in the case of iOS and OS X.)

As a result, converting a date from Gregorian to Hijri doesn't do anything because that fixed moment remains the same.

If you tell us specifically what transformation you expect to occur between Gregorian and Hijri that is not already occurring, we can suggest an alternate course of action.



回答2:

You don't have to make any conversions at all.

NSLog prints object's description method. Since NSDate stores only amount of seconds since reference date and does not keep a track of calendar it belongs to, it uses Gregorian calendar to format date for description method.

Customize NSDateFormatter to use your calendar and use stringFromDate: to get localized string value for your date.