在 Objective-C 中使用 NSDateFormatter | 珊瑚贝

Using NSDateFormatter in objective-C

本问题已经有最佳答案,请猛点这里访问。


我想使用 nsdateformatter.

将 2013-07-10T21:48:09.000Z 转换为 10.7.2013

我已经尝试过一些教程,但我似乎无法弄清楚该怎么做,我该如何正确地进行这种转换?

非常感谢任何帮助。

我试过这个,但我只得到一个 (null)

1
2
3
4
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@“yyyy-MM-dd’T’HH:mm:000Z”];
    NSDate *theDate = [dateFormatter dateFromString:stringDate];
    NSLog(@“%@”,[dateFormatter stringFromDate:theDate]);
  • 请链接到您使用的教程
  • 看看这里,例如:stackoverflow.com/questions/3094819/…
  • 您的格式中缺少秒部分。
  • 我错过了什么?
  • Z 如果您希望它是文字”Z”,则需要在其周围加上引号,因为 Z 用作时区格式字符。
  • 阅读 NSDateFormatter 的规范。并按照其中的链接通过几个页面到达描述格式字符串的位置。然后搜索数以千计的关于 NSDateFormatter 的问题,这些问题是由以前的人写的,他们和你一样,没有做这项基础研究。
  • 在您上面的代码片段中,您是否进行了最少的调试,以查看您是否从 dateFromString 操作中获得了良好的结果,将您的问题分成两半?


首先,你的日期格式错误——第二行应该是[dateFormatter setDateFormat:@”yyyy-MM-dd’T’HH:mm:ss.000Z”];——也就是说,你需要在mm:之后但在000Z之前的ss.。这将为您提供正确的 NSDate。

接下来,您需要创建一个格式为 @”dd.M.yyyy” 的新日期格式化程序(或者如果您想删除前导零,如果日期也是一位数,则为 @”d.M.yyyy”)并在其上调用 stringFromDate: NSLog.

回顾一下,整个代码块将是

1
2
3
4
5
6
7
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@“yyyy-MM-dd’T’HH:mm:ss.000Z”];
NSDate *theDate = [dateFormatter dateFromString:stringDate];

NSDateFormatter *printFormatter = [[NSDateFormatter alloc] init];
[printFormatter setDateFormat:@“dd.M.yyyy”];
NSLog(@“%@”,[printFormatter stringFromDate:theDate]);

  • 它返回了\\’2013-07-10T21:48:09.000 0000\\’,我需要它返回\\’10.7.2013\\’
  • @IamGretar 哎呀,没听懂——我以为你只是想要正确的 NSDate。我已经更新了我的答案。
  • 不需要是新的 NSDateFormatter – 只需将新格式设置为旧格式。
  • @HotLicks 好点,这也很有效(并且省去了分配另一个 NSDateFormatter 实例的麻烦)。


来源:https://www.codenong.com/17621435/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9961.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?