【问题标题】:How to get date from a string (iPhone)?如何从字符串(iPhone)中获取日期?
【发布时间】:2010-12-06 07:23:05
【问题描述】:
I need to convert this string in to the date:

    02-09-2011 20:54:18

I am trying the `dateFromString` method but every time it is returning (null), what NSDateFormatter should I use?, I have tried
`[formatter setDateFormat:@"yyyy-MM-dd"]` and `[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]`.


Here is my code:
NSString *finalDate = @"02-09-2011 20:54:18";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSDate *dateString = [formatter dateFromString:finalDate];
NSLog(@"%@",dateString);


Thanks.

【问题讨论】:

  • 有一段时间我认为这是某种计算机科学问题,关于一种叫做“大叶形式”的东西......你让我失望了:(
  • 没有人可以制作大叶表单字符串。
  • 为什么要设置两次日期格式。给出解决方案的代码,你肯定会犯一些愚蠢的错误
  • 为什么不给一些你遇到问题的代码。并且也对不同的情况有所不同。

标签: iphone string nsdateformatter date-format


【解决方案1】:

您可以使用带有以下代码的 NSDateFormatter 将包含日期的 NSString 转换为 NSDate:

// Your date as a string
NSString *finalDate = @"02-09-2011 20:54:18";

// Prepare an NSDateFormatter to convert to and from the string representation
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// ...using a date format corresponding to your date
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

// Parse the string representation of the date
NSDate *date = [dateFormatter dateFromString:finalDate];

// Write the date back out using the same format
NSLog(@"Month %@",[dateFormatter stringFromDate:date]);

【讨论】:

  • 非常感谢,你的答案正是我正在寻找的,我期待你在日期格式中出现错误,我搜索了很多正确的日期格式但没有再次得到感谢:- )
  • 将字符串转换为 Date 对象会返回 GMT(格林威治标准时间)中的日期。
【解决方案2】:

搜索肯定比问容易吗?

How do I convert from NSString to NSDate?

【讨论】:

    猜你喜欢
    • 2015-05-13
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多