看过某书上面的做法是先生成一个公历的calendar,使用的是:
NSCalendar *cal = [NSCalendar currentCalendar];
然后用它生成一个NSDateComponent,最后再用一个中国农历的calendar将NSDateComponent转换为一个农历的NSDate。
实际执行后发现转换后的日期是错的。
下面是一个正确的转换方法,关键在于:先生成一个农历的calendar,然后再转换为公历的表示:
voID show_local_date(NSDate *date){ NSDateFormatter *f = [NSDateFormatter new]; [f setDateFormat:@"Y-M-d HH:mm:ss z"]; [f setTimeZone:[NSTimeZone timeZoneWithname:@"GMT+8"]]; NSLog(@"%s:date is %@",__func__,[f stringFromDate:date]);}int main(voID){ @autoreleasepool{ NSLog(@"Now is %@",[NSDate new]); NSCalendar *chinese_cal = [[NSCalendar alloc] initWithCalendarIDentifIEr: NSCalendarIDentifIErChinese]; [chinese_cal setTimeZone:[NSTimeZone timeZoneWithname:@"GMT+8"]]; unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |\ NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; NSDateComponents *comps = [chinese_cal components:unitFlags fromDate:[NSDate new]]; NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *china_Now = [cal dateFromComponents:comps]; show_local_date(china_Now); NSLog(@"%@",[Foo getChineseCalendarWithDate:[NSDate new]]); } return 0;}
最后是其他人写的转换代码,和我的类似:
+(Nsstring*)getChineseCalendarWithDate:(NSDate *)date{ NSArray *chineseYears = [NSArray arrayWithObjects: @"甲子",@"乙丑",@"丙寅",@"丁卯",@"戊辰",@"己巳",@"庚午",@"辛未",@"壬申",@"癸酉",@"甲戌",@"乙亥",@"丙子",@"丁丑",@"戊寅",@"己卯",@"庚辰",@"辛己",@"壬午",@"癸未",@"甲申",@"乙酉",@"丙戌",@"丁亥",@"戊子",@"己丑",@"庚寅",@"辛卯",@"壬辰",@"癸巳",@"甲午",@"乙未",@"丙申",@"丁酉",@"戊戌",@"己亥",@"庚子",@"辛丑",@"壬寅",@"癸丑",@"甲辰",@"乙巳",@"丙午",@"丁未",@"戊申",@"己酉",@"庚戌",@"辛亥",@"壬子",@"甲寅",@"乙卯",@"丙辰",@"丁巳",@"戊午",@"己未",@"庚申",@"辛酉",@"壬戌",@"癸亥",nil]; NSArray *chineseMonths=[NSArray arrayWithObjects: @"正月",@"二月",@"三月",@"四月",@"五月",@"六月",@"七月",@"八月",@"九月",@"十月",@"冬月",@"腊月",nil]; NSArray *chineseDays=[NSArray arrayWithObjects: @"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十",nil]; NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIDentifIEr:NSCalendarIDentifIErChinese]; unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |\ NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date]; NSLog(@"%ld_%ld_%ld %@",localeComp.year,localeComp.month,localeComp.day,localeComp.date); Nsstring *y_str = [chineseYears objectAtIndex:localeComp.year-1]; Nsstring *m_str = [chineseMonths objectAtIndex:localeComp.month-1]; Nsstring *d_str = [chineseDays objectAtIndex:localeComp.day-1]; Nsstring *chineseCal_str =[Nsstring stringWithFormat: @"%@_%@_%@",y_str,m_str,d_str]; //[localeCalendar release]; return chineseCal_str;}总结
以上是内存溢出为你收集整理的Cocoa公历和中国农历直接的转换全部内容,希望文章能够帮你解决Cocoa公历和中国农历直接的转换所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)