是否可以定义一个适应可变数据的日期格式?
我需要找到一种可以适应以下两个日期的日期格式:
2012-01-22T14:27:31.176+0000
2012-01-22T14:27:31+0000
code>
如您所见,唯一的区别是日期 2 没有秒小数部分。
两种日期格式为:
yyyy-MM-dd'T'HH:mm:ss.SZ
yyyy-MM-dd'T'HH:mm:ssZ
以及第二个省略 .S。
是否可以使 .S 可选?或者我必须继续使用两种不同的格式?
问题在于,我从 API 调用中获取日期,有时它带有小数秒,有时则没有。
我想我可以检测小数位的存在并相应地使用两种不同的日期格式,但我一直在寻找更干净的解决方案。
谢谢!
I need to find a date format which could adapt to the two following dates:
2012-01-22T14:27:31.176+0000
2012-01-22T14:27:31+0000
As you can see, the only difference is that date 2 does not have the fractional seconds.
The two date formats would be:
yyyy-MM-dd'T'HH:mm:ss.SZ
yyyy-MM-dd'T'HH:mm:ssZ
with the second one omitting .S.
Is it possible to make .S optional? Or do I have to keep using 2 different formats?
The problem lies in the fact that I'm getting the date from an API call, and sometimes it comes with the fractional seconds, other times without.
I guess I could detect the presence of the decimal place and use the two different date formats accordingly, but I was looking for a cleaner solution.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将
NSDateFormatter
的lenient
属性设置为YES
,这允许NSDateFormatter
对您的输入进行猜测细绳。但是,您应该对此进行测试,因为它可能会给您带来一些误报。You can set the
NSDateFormatter
'slenient
property toYES
which allows theNSDateFormatter
to take a guess on your input string. However, you should test this since it might give you some false positives.嗯,第一件事可能是查看数据的实际长度。不干净,但应该可以工作
Well, the first thing could be to look at the actual length of the data. Not clean, but should work
您可以测试字符串的长度,然后根据长度使用两种不同的日期格式化程序之一吗?
Could you test the length of the string and then use one of 2 different date formatters depending on the length?
我将有两个日期格式化程序,然后根据日期字符串中是否有小数位来选择要使用的日期格式化程序。
我不认为有一个格式字符串可以使小数成为可选的
或者您可以只使用带有小数秒的格式字符串,没有小数秒的日期只会在末尾显示 .00,可能看起来更一致?
I would have two date formatters, and then choose the date formatter to use depending on wether there is a decimal place or not in your date string.
I dont think there is a format string that would make the decimal optional
Alternatively you could just use the format string with the fractional seconds, your dates without fractional seconds would just display with a .00 on the end, might look more consistent?
在这种情况下,@JustSid 建议的“宽松”属性不起作用。
由于没有找到“更干净”的解决方案,我回到了第一个解决方案,即检测小数位的存在并相应地使用两种不同的日期格式。
The "lenient" property suggested by @JustSid in this case did not work.
Having not found a "cleaner" solution, I went back to my first one, which was detecting the presence of the decimal place and using the two different date formats accordingly.