如何使用NSDateFormatter和可选的毫秒部分解析ISO 8601 [英] How to parse ISO 8601 using NSDateFormatter with optional milliseconds part

查看:74
本文介绍了如何使用NSDateFormatter和可选的毫秒部分解析ISO 8601的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NSDateFormatter来解析这些格式中的任何一种日期

I'm trying to use an NSDateFormatter to parse dates that are in either of these formats

@"2013-02-01T14:21:00"

@"2013-02-01T14:21:56.345"

目前我使用下面的方法来解析字符串并返回日期:

Currently I am using the below method to parse the string and return a date:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [dateFormatter dateFromString:dateToFormat];

这适用于第一种日期样式,但对于包含毫秒部分的字符串返回nil。

This works fine for the first style of date but returns nil for a string that includes the milliseconds part.

我想我可以测试是否存在毫秒并剥离它们但是我想知道我是否可以更改日期格式以将.SSS视为可选项?

I suppose I could test for the existence of the milliseconds and strip them but I was wondering if I could change the date format to treat the .SSS as optional?

感谢您的帮助

推荐答案

据我所知,没有制作可选参数的方法。

As far as I know there is no way to make optional parameters.

通常的解决方案是使用两个格式化程序,每种格式一个。
要决定使用哪种格式化程序,您可以

The usual solution is to use two formatters, one for each format. To decide which formatter to use, you can either


  1. 计算日期字符串中的字符数(如建议使用使用NSDateFormatter解析RFC 822日期

只需尝试两种格式化程序并获得第一个非 nil 结果。

Just try both formatters and get the first non-nil result.

由于您的日期格式相似,您只能使用一个格式化程序,如果日期字符串太短,请附加 .000 在使用格式化程序之前。

Since your date formats are similar, you can go with only one formatter and if the date string is too short, append .000 before using the formatter.

这篇关于如何使用NSDateFormatter和可选的毫秒部分解析ISO 8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆