How to convert a Buddhist date to a Gregorian date

How to convert Jan 27, 2557 Buddhist date on January 27, 2013 .

Yes, I know that if I subtract 543 from 2557, I get 2014. However, I want it to be solved using NSDateFormatter.

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

Thanks.

+4
source share
2 answers

This is pretty much copying / pasting from Apple documents with minor changes to use the correct calendar types. I hardcode the date for 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
source

Create an instance of the Gregorian calendar, then use NSDateFormatter to format it.

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

print(dateFormatter.stringFromDate(NSDate()))
0

Source: https://habr.com/ru/post/1523839/


All Articles