从整数组装日期对象?

发布于 2024-10-13 02:50:55 字数 42 浏览 4 评论 0原文

给定三个整数,分别代表日、月和年,什么代码会将这些整数组装成日期对象?

Given three integers, representing a day, month and year, what code would assemble those integers into a date object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唱一曲作罢 2024-10-20 02:50:56

您应该查看NSDateComponents

int y = 2011;
int m = 1;
int d = 15;


NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:y];
[dc setMonth:m];
[dc setDay:d];

NSLog(@"%@: %@", [[dc date] class], [dc date]);

You should look at NSDateComponents:

int y = 2011;
int m = 1;
int d = 15;


NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:y];
[dc setMonth:m];
[dc setDay:d];

NSLog(@"%@: %@", [[dc date] class], [dc date]);
往日 2024-10-20 02:50:56

NSDateFormatter 使用用于将日期字符串解析为日期的 Unicode 标准。因此,将整数格式化为日期字符串,然后使用 NSDateFormatter 来解析它:

// assume year, month and day are integers that are formatted properly and don't
// include invalid ranges
NSString* dateString = [NSString stringWithFormat:@"%04d %02d %02d", year, month, day];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
// Choose a format of YEAR MONTH DATE per the standard
[formatter setDateFormat:@"yyyy MM dd"];
NSDate* date = [formatter dateFromString:dateString];
[formatter release];

只要使用 Unicode 标准(上面链接)并将整数转换为相同的格式(显然)。

NSDateFormatter uses the Unicode Standard for parsing date strings into dates. So, format your integers into a date string and then use and NSDateFormatter to parse it:

// assume year, month and day are integers that are formatted properly and don't
// include invalid ranges
NSString* dateString = [NSString stringWithFormat:@"%04d %02d %02d", year, month, day];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
// Choose a format of YEAR MONTH DATE per the standard
[formatter setDateFormat:@"yyyy MM dd"];
NSDate* date = [formatter dateFromString:dateString];
[formatter release];

You can set the format string to whatever format floats your boat, as long as you use the Unicode Standard (linked above) and you convert your integers into the same format (obviously).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文