将日期的 NSString 转换为 NSDate

发布于 2024-10-05 18:21:03 字数 233 浏览 0 评论 0原文

这可能是一个愚蠢的问题,但我似乎无法在这里或文档中找到答案。

我想将 NSString 例如 @"9/22/2010 3:45 PM" 转换为 NSDate。

我知道使用 NSDateFormatter,但问题是

  1. 月份可能是一位或两位数字
  2. 同样,日期可能是一位或两位数字
  3. 小时可能是一位或两位数字
  4. 我该怎么处理 AM/PM?

This might be a silly question, but I can't seem to find the answer on here or in the documentation.

I want to convert an NSString such as @"9/22/2010 3:45 PM" to an NSDate.

I know to use NSDateFormatter, but the problems are

  1. The month could be one or two digits
  2. Likewise, the date could be one or two digits
  3. Hours could be one or two digits
  4. What do I do about AM/PM?

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

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

发布评论

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

评论(3

不即不离 2024-10-12 18:21:03
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];

2 位数的日或 2 位数的月没有问题。

这一定对你有帮助。

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];

there is no problem in 2 digit day or 2 digit month.

This must help you.

没︽人懂的悲伤 2024-10-12 18:21:03

您可以使用 NSDateFormatter 类将 NSString 解析为 NSDate。请参阅文档 欲了解更多信息:

NSDateFormatter 的实例创建 NSDate(和 NSCalendarDate)对象的字符串表示形式,并将日期和时间的文本表示形式转换为 NSDate 对象。

You can parse an NSString into an NSDate using the NSDateFormatter class. See the documentation for more info:

Instances of NSDateFormatter create string representations of NSDate (and NSCalendarDate) objects, and convert textual representations of dates and times into NSDate objects.

梨涡少年 2024-10-12 18:21:03

我遇到了同样的问题,不知道为什么 NSDateFormatter 不适合我(iOS5 - Xcode 4.3.2),但这对我来说很有效:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = @"05-06-2012";
NSDate *date;
NSError *error = nil; 
if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
    NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
}
[dateFormatter release];

I was having the same problem, not sure why NSDateFormatter isn't working for me (iOS5 - Xcode 4.3.2) but this worked out for me:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = @"05-06-2012";
NSDate *date;
NSError *error = nil; 
if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
    NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
}
[dateFormatter release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文