将 NSString 转换为 NSDate

发布于 2024-09-27 05:04:38 字数 105 浏览 1 评论 0原文

我有日期字符串:2010 年 10 月 11 日星期一。如何从中创建一个 NSDate 对象,然后从中获取不同的组件,例如日、月、日期、年。请注意,该字符串的格式/区域设置可能会在运行时发生变化。

I have date string: Monday, October 11, 2010. How can I create a NSDate object out of it and then get different components like day, month, date, year from it. Please note that format/locale of this string may change at runtime.

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

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

发布评论

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

评论(2

反目相谮 2024-10-04 05:04:38

使用 NSDateFormatter 创建 NSDate,然后您可以通过 NSDate 属性访问其组件(您需要调整下面的格式字符串):

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

if(NSDate *myDate = [df dateFromString:string]) {
    //Do something with myDate
}

Use an NSDateFormatter to create the NSDate, then you can access its components through NSDate properties (you'll need to adjust the format string below):

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

if(NSDate *myDate = [df dateFromString:string]) {
    //Do something with myDate
}
燕归巢 2024-10-04 05:04:38

另一种可能性:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...

another possibility:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文