Convert NSDates from one calendar to another

混江龙づ霸主 提交于 2019-12-25 04:02:59

问题


There are lots of questions with the same title but none has answered my question. I want to be able to convert a NSString that represents Islamic calendar to a NSDate that displays that date in Gregorian calendar. This is the code that i have but it still returns the NSDate in Islamic Calendar.

- (NSDate*) convertToNSDateFromString : (NSString *)dateString : (NSString *)dateFormat
{
//Format the Calendar
NSDateFormatter *f = [[NSDateFormatter alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
[f setCalendar:gregorian];
[f setDateStyle:NSDateFormatterLongStyle];
[f setDateFormat:dateFormat];

NSDate *date = [f dateFromString:dateString];

return date;
}

回答1:


The NSDate does not have a calendar. This is actually a time stamp representing a certain time. Try reading a bit about EPOCH to get a better understanding.

Anyway a NSDate can give you a duration in seconds from a reference time using timeIntervalSince1970 this will return a number of seconds from 1.1.1970 UTC and this is actually all what the NSDate is. That means there are no magic tools to work on this object at all.

What you need beside this object is a calendar, a NSCalendar should do the trick. This calendar can help you convert the time representation but not the time itself. So all you can do with it is to convert a time stamp to a different representation of the date or you can get a time stamp from a certain representation of the date. Why this is so is because most of the time you can find 24 locations on earth where each of them have a different current time due to the time zone... It is not that I think you do not know this, just trying to explain why date tools are so complex and hard to use.



来源:https://stackoverflow.com/questions/26100657/convert-nsdates-from-one-calendar-to-another

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