How to convert buddhist Date To Gregorian Date Properly iOS

亡梦爱人 提交于 2019-12-10 16:13:16

问题


How to convert Jan 27, 2557 a Buddhist date into Jan 27, 2013.

Yes, I'm aware that If I subtract 543 from 2557 I'll get 2014. However, I want it to solve using NSDateFormatter.

Here my code:

dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

 TimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"];

// Buddhist date should be converted to Gregorian date. But the
// Date still in Buddhist form
NSDate *gregDate = [dateFormatter dateFromString:buddhistDate];

Thank you.


回答1:


This is pretty much copy/paste from the Apple docs, with a minor change to use the correct calendar types. I'm hardcoding the date to the values you used in your example.

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:27];
[comps setMonth:1];
[comps setYear:2557];

NSCalendar *buddhist = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSBuddhistCalendar];
NSDate *date = [buddhist dateFromComponents:comps];

NSCalendar *gregorian = [[NSCalendar alloc]
                      initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMonthCalendarUnit |
NSYearCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:date];

NSInteger day = [components day]; 
NSInteger month = [components month];
NSInteger year = [components year];



回答2:


Create the instance of Gregorian calendar then use NSDateFormatter to format with it

let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateFormatter = NSDateFormatter()
dateFormatter.calendar = gregorianCalendar
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"

print(dateFormatter.stringFromDate(NSDate()))


来源:https://stackoverflow.com/questions/21373441/how-to-convert-buddhist-date-to-gregorian-date-properly-ios

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