开发者

Parse non-standard date format like "+0yyyyMMdd"

开发者 https://www.devze.com 2023-01-05 07:01 出处:网络
I Have Date, that comes to our system in format +0yyyyMMdd For instance 12 March,2011 is +020110312 For now it\'s开发者_开发百科 definitely + symbol and one 0 before Date, but in future it may be mo

I Have Date, that comes to our system in format +0yyyyMMdd

For instance 12 March,2011 is +020110312

For now it's开发者_开发百科 definitely + symbol and one 0 before Date, but in future it may be more than one zeros,e.g. +000020110312

Is it possible to parse it with standard 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:

new SimpleDateFormat("ZyyyyddMM")

Alas, this doesn't work immediately.

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. See SimpleDateFormat


If the +0 prefix is a constant, then you can just quote it using singlequotes.

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. The mm represents minutes. Using mm for months would corrupt the parsing outcome.

See also:

  • SimpleDateFormat javadoc

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.

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. (I am not sure if you can safely avoid it)


You could parse the date portion using SimpleDateFormat.

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

But you would need to strip off the "+000" prefix.

0

精彩评论

暂无评论...
验证码 换一张
取 消