C++ 使用ICU解析带有可选分数秒的ISO 8601日期时间
我使用了C++ 使用ICU解析带有可选分数秒的ISO 8601日期时间,c++,icu,iso8601,C++,Icu,Iso8601,我使用了yyyy-MM-dd'T'HH:MM:ss.SSSXXX格式字符串和icu::SimpleDateFormat 虽然它适用于带有小数位数的日期时间字符串。示例: 2016-03-31T15:04:32.049Z 2016-03-31T15:04:32.05Z 2016-03-31T15:04:32.3Z 它不会在没有小数秒的情况下解析字符串(例如,2016-03-31T15:08:51Z),返回错误代码U\U非法参数U错误 我尝试了一些其他的格式组合,但没有成功:一些组合失败,出现错误代
yyyy-MM-dd'T'HH:MM:ss.SSSXXX
格式字符串和icu::SimpleDateFormat
虽然它适用于带有小数位数的日期时间字符串。示例:
2016-03-31T15:04:32.049Z
2016-03-31T15:04:32.05Z
2016-03-31T15:04:32.3Z
它不会在没有小数秒的情况下解析字符串(例如,2016-03-31T15:08:51Z
),返回错误代码U\U非法参数U错误
我尝试了一些其他的格式组合,但没有成功:一些组合失败,出现错误代码,其他组合忽略毫秒
ICU甚至支持解析可选的分数秒吗?通过ICU,我没有找到任何方法在模式规范中输入可选部分
但是,这个问题可以在应用程序级别以多种不同的方式解决。其中一种方法(简化)是使用多个datetime解析器,如下所示:
#include <iostream>
#include <vector>
#include "unicode/datefmt.h"
#include "unicode/smpdtfmt.h"
int main() {
UErrorCode err(U_ZERO_ERROR);
UnicodeString patternWithMilliseconds("yyyy-MM-dd'T'hh:mm:ss.SSSXXX");
UnicodeString patternPlane("yyyy-MM-dd'T'hh:mm:ssX");
// init ICU parsers
std::vector<SimpleDateFormat*> parsers = {
new SimpleDateFormat(patternWithMilliseconds, err),
new SimpleDateFormat(patternPlane, err)
};
// get dates to convert
std::vector<UnicodeString> dates = {
UnicodeString("2016-03-31T15:04:32.049Z"),
UnicodeString("2017-10-30T15:05:33Z"),
};
SimpleDateFormat resultFormatter(patternWithMilliseconds, err);
for(const auto& date : dates) {
UDate parsedDate;
UnicodeString result;
std::string resultConverted;
for(const auto& parser : parsers) {
err = U_ZERO_ERROR;
parsedDate = parser->parse(date, err);
if (err <= 0) break;
}
resultFormatter.format(parsedDate, result);
result.toUTF8String(resultConverted);
std::cout << resultConverted << std::endl;
}
for(auto& parser : parsers) {
delete parser;
}
return 0;
}
#包括
#包括
#包括“unicode/datefmt.h”
#包括“unicode/smpdtfmt.h”
int main(){
用户错误代码错误(U_零_错误);
以毫秒为单位的破坏模式(“yyyy-MM-dd'hh:MM:ss.SSSXXX”);
单色图案平面(“yyyy-MM-dd'T'hh:MM:ssX”);
//初始化ICU解析器
std::向量解析器={
新的SimpleDataFormat(PatternWithMillimes,err),
新SimpleDataFormat(patternPlane,err)
};
//获取要转换的日期
标准::矢量日期={
独角兽毁灭(“2016-03-31T15:04:32.049Z”),
独角兽破坏(“2017-10-30T15:05:33Z”),
};
SimpleDataFormat resultFormatter(PatternWith毫秒,错误);
用于(常数自动和日期:日期){
UDate-parsedDate;
破坏结果;
std::字符串结果转换;
for(常量自动&解析器:解析器){
err=U_零_错误;
parsedDate=parser->parse(日期,错误);
if(err)这将使用语法字符串%FT%TZ执行
。只需解析成一个std::chrono::system\U clock::time\U point
。我希望最终的解决方案是尝试使用多个解析器进行解析…首先使用指定秒数的解析器,然后不使用。然而,我在尝试此操作时也遇到了U\U非法参数错误,因此我不确定该怎么做我也错了。我希望问题是相似的,所以我在这上面悬赏。我使用的格式是