Skip to content

Instantly share code, notes, and snippets.

@jjgod
Created December 22, 2009 07:30
Show Gist options
  • Save jjgod/261583 to your computer and use it in GitHub Desktop.
Save jjgod/261583 to your computer and use it in GitHub Desktop.
// test.m: test calendar code
// Compile with: gcc -Wall -framework Foundation test.m -o test
#import <Foundation/Foundation.h>
NSString *ChineseYear(int year)
{
const char *tiangan[] = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
const char *dizhi[] = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
char buffer[10];
sprintf(buffer, "%s%s", tiangan[(year - 1) % 10], dizhi[(year - 1) % 12]);
return [NSString stringWithUTF8String: buffer];
}
NSString *ChineseMonth(int month)
{
const char *months[] = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊" };
return [NSString stringWithUTF8String: months[(month - 1) % 12]];
}
NSString *ChineseDay(int day)
{
const char *digits[] = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
char buffer[10];
if (day <= 10)
sprintf(buffer, "初%s", digits[day - 1]);
else if (day > 10 && day < 20)
sprintf(buffer, "十%s", digits[(day - 1) % 10]);
else if (day == 20 || day == 30)
sprintf(buffer, "%s十", digits[day / 10]);
else if (day > 20 && day < 30)
sprintf(buffer, "廿%s", digits[(day - 1) % 10]);
return [NSString stringWithUTF8String: buffer];
}
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSCalendar *chinese = [[NSCalendar alloc] initWithCalendarIdentifier: NSChineseCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [chinese components:unitFlags fromDate:date];
NSLog(@"comps: %@年%@月%@",
ChineseYear([comps year]),
ChineseMonth([comps month]),
ChineseDay([comps day]));
[chinese release];
[pool release];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment