Tutorial :Parse non-standard date format like “+0yyyyMMdd”



Question:

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.


Solution:1

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:


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  


Solution:2

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


Solution:3

I would substring the last 8 chars from your representation and then parse it. (I am not sure if you can safely avoid it)


Solution:4

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »