简体   繁体   English

解析非标准日期格式,例如“ + 0yyyyMMdd”

[英]Parse non-standard date format like “+0yyyyMMdd”

I Have Date, that comes to our system in format +0yyyyMMdd 我有日期,以+ 0yyyyMMdd格式出现在我们的系统中

For instance 12 March,2011 is +020110312 例如,2011年3月12日为+020110312

For now it's definitely + symbol and one 0 before Date, but in future it may be more than one zeros ,eg +000020110312 目前,它肯定是+符号,并且在Date之前是一个0 ,但将来可能是多个 ,例如+000020110312

Is it possible to parse it with standard Java java.text.DateFormat.parse(String source) ? 是否可以使用标准Java java.text.DateFormat.parse(String source)对其进行解析?

Or I should write custom parsing method? 还是我应该编写自定义解析方法?

Thank you. 谢谢。

I'd guess the +0 is a timezone indicator, so you can try: 我猜想+0是时区指示器,因此您可以尝试:

new SimpleDateFormat("ZyyyyddMM")

Alas, this doesn't work immediately. las,这无法立即生效。

In order to make it work, get a substring from 0 to length - 8 and expand it to be four digits to meet the RFC for the timezone. 为了使其工作,请获取从0length - 8的子字符串length - 8 ,并将其扩展为四位数字,以满足时区的RFC。 See SimpleDateFormat 参见SimpleDateFormat

If the +0 prefix is a constant, then you can just quote it using singlequotes. 如果+0前缀是常量,则可以使用单引号将其引起来。

String string = "+020110312";
Date date = new SimpleDateFormat("'+0'yyyyMMdd").parse(string);
System.out.println(date); // Sat Mar 12 00:00:00 GMT-04:00 2011

(outcome is correct as per my timezone) (根据我的时区,结果是正确的)

Note that months are represented by MM not mm . 请注意,月份以MM而非mm表示。 The mm represents minutes. mm代表分钟。 Using mm for months would corrupt the parsing outcome. 使用mm数月会破坏解析结果。

See also: 也可以看看:


Update : since that seem to vary in the future "but in future it may be more than one zeros" , you can better consider to substring the last 8 characters. 更新 :由于将来似乎有所不同, “但将来可能会超过一个零” ,因此您最好考虑对最后8个字符进行子字符串化。

String string = "+020110312";
Date date = new SimpleDateFormat("yyyyMMdd").parse(string.substring(string.length() - 8));
System.out.println(date); // Sat Mar 12 00:00:00 GMT-04:00 2011

I would substring the last 8 chars from your representation and then parse it. 我会将您的表示形式的最后8个字符细分为字符串,然后对其进行解析。 (I am not sure if you can safely avoid it) (我不确定您是否可以安全避免这种情况)

You could parse the date portion using SimpleDateFormat. 您可以使用SimpleDateFormat解析日期部分。

SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.parse("20110312");

But you would need to strip off the "+000" prefix. 但是您将需要去除“ +000”前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM