views:

52

answers:

5

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.

A: 

why not parse a substring of the last 8 characters?

Alexander
A: 

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

Grzenio
+4  A: 

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

Bozho
`java.text.ParseException: Unparseable date: "+020110312"` :/
BalusC
@BalusC, yes, just tested it; see update
Bozho
thank your for good point
sergionni
A: 

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.

BrennaSoft
+2  A: 

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
BalusC
thank your for assistance
sergionni
You're welcome.
BalusC