【问题标题】:NSDate returning nil when converting from string从字符串转换时 NSDate 返回 nil
【发布时间】:2015-01-21 02:14:45
【问题描述】:

我正在尝试从日期字符串中获取时间。以下字符串应返回 12:00AM。

2010-08-24 00:00:00 +0000

但是使用下面的代码,我的 NSDate 对象在到达日志语句时返回 nil。这里有什么问题?谢谢!

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"h:mma"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

输出:日期:(空)

【问题讨论】:

  • 这是因为您传递的日期格式(字符串)与日期格式不匹配....尝试使用相同的日期格式....
  • 为什么没有人查阅文档??
  • @HotLicks ...因为他们可以让某人在 SO 上为他们查找。
  • 你接受了一个错误的答案。

标签: ios objective-c nsdate


【解决方案1】:

试试这个:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"YYYY-MM-dd hh:mm:ss ZZZZ"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

干杯!

在 playgorund 上测试:

【讨论】:

  • 谢谢,但我怎样才能返回一天中的时间?
  • [NSDate 日期]; // 返回今天日期
  • (转换"2010-01-01 23:42:00 +0000")
【解决方案2】:

您可以使用以下过程从日期字符串中提取时间

1.获取给定格式的 NSDate 对象。

2.将 NSDateFormatter 对象设置为所需的格式。

3.获取所需格式的日期字符串。

 - (BOOL)application:(UIApplication *)
application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    NSString *date = [self convertDate:@"2010-08-24 00:00:00 +0000"
                            fromFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"
                              toFormat:@"hh:mm a"];

    NSLog(@"DATE: %@", [date description]);

    return YES;
}


- (NSString *)convertDate:(NSString *)inDateString
             fromFormat:(NSString *)fromFormat
               toFormat:(NSString *)toFormat
{
    NSDateFormatter *dateFormatter = nil;
    NSString *outDateString = nil;
    NSDate *date = nil;

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:fromFormat];

    date = [dateFormatter dateFromString:inDateString];

    [dateFormatter setDateFormat:toFormat];
    outDateString = [dateFormatter stringFromDate:date];

    return outDateString;
}

【讨论】:

  • 您的日期格式不正确(虽然不如其他格式不正确)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 2015-07-09
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多