Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The incredible java time machine [duplicate]

What happens to my time/date using this sample code??

package date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormatTest
{
    public static void main(String args[]) throws ParseException
    {
        final String pattern = "dd/MM/YYYY HH:mm";
        final Locale locale = Locale.FRENCH;
        final SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);

        Date d = new Date();
        System.out.println("Today: " + d);

        String parsedDate = formatter.format(d);
        System.out.println("Today as string:" + parsedDate);

        Date d2 = formatter.parse(parsedDate);
        System.out.println("Today parsed back:" + d2);

    }
}

Output:

Today: Fri Jun 28 16:28:04 CEST 2013
Today as string:28/06/2013 16:28
Today parsed back:Mon Dec 31 16:28:00 CET 2012    >>> ????
like image 333
remi Avatar asked Aug 24 '26 09:08

remi


2 Answers

pattern = "dd/MM/YYYY HH:mm";

should be

pattern = "dd/MM/yyyy HH:mm";

See JavaDoc.

But note that this code as you posted does not even run on my Eclipse:

java.lang.IllegalArgumentException: Illegal pattern character 'Y'

Ah, Y is added in Java 7. But it is weekyear.

like image 90
zw324 Avatar answered Aug 26 '26 22:08

zw324


Little explanation, but is only a guessing, correct me if I'm wrong.

As the explanation of week year I guess that parsing the week year of 2013 (due to the wrong pattern 2013 -> YYYY ) is somehow setting the whole date to the first week year of the 2013, that is Monday 31/12/2012.

like image 22
Enrichman Avatar answered Aug 26 '26 21:08

Enrichman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!