Reputation: 1044
My controller recieves this String "20120115Z" as a @RequestParam, representing a date.
I would like to transform it to this format: yyyy-MM-dd, so I would have a new string like this 2012-01-15.
As you can see, there's no delimiters, only the 'Z' always as the last character.
My approach was pretty obvious:
String data =
strData.substring(0, 4) + "-" +
strData.substring(4, 6) + "-" +
strData.substring(6, 8);
And it works, but as you know these "magic numbers" are something to avoid. I also tried to use a a regular expression like "^[^\s]{4}[^\s]{2}[^\s]{2}Z$", but without success.
Any idea?
UPDATE: Finally I've done it with Joda-Time DateTime class as @Brian Agnew suggested
DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYYMMdd'T'hhmm'Z'");
String strData = "20120115T0600Z";
DateTime dt = fmt.parseDateTime(strData);
printing method:
private static void printDateTime(DateTime dt) {
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
int hour = dt.getHourOfDay();
int minute = dt.getMinuteOfHour();
int second = dt.getSecondOfMinute();
int millis = dt.getMillisOfSecond();
String zone = dt.getZone().toString();
log.info("fecha: "
+ day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + millis
+ " " + zone + "\n");
}
Output
15/1/2012 6:0:0:0 UTC
Thanks everyone
Upvotes: 0
Views: 2561
Reputation: 272257
I would perhaps use a Joda-Time DateTimeFormat.
Why ? It'll check the format, including valid values for hours/minutes/seconds, and give you back a suitable DateTime object which you can do what with (including reformat it using a similar approach).
You simply give it the format that you want to parse and it'll do all the rest. You have a date, so treat it as such.
Upvotes: 4