Parsing Java String to date

2019-07-24 15:09发布

问题:

log(2 different dates):

START TIME BEFORE PARSE: 06/27/2012 09:00
START TIME AFTER PARSE : Thu Mar 06 09:00:00 EET 2014


START TIME BEFORE PARSE: 07/06/2012 09:00
START TIME AFTER PARSE : Thu Jun 07 09:00:00 EEST 2012

code :

DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            Date date = sdf.parse(time);
            System.out.println("TIME BEFORE PARSE: " + time);
            System.out.println("TIME AFTER PARSE : " + date);

Why does it mess up the year? How to get it to work?

回答1:

Because you inverted the month with the date:

              dd/MM/yyyy HH:mm
              06/27/2012 09:00

There is not 27th month in a year.



回答2:

The month in the first example is 27 which isn't valid in any calendar I'm aware of. (You probably just got the day/month ordering wrong, either on your input, or in the format you've chosen.)



回答3:

You use the pattern dd/MM/yyyy to parse the date 06/27/2012. I doubt 27 is a month. The appropriate format is MM/dd/yyyy.

The DateFormat is lenient by default, and will thus consider 27 as a valid month: 2 years + 3 months, so you end up in March, 2 years later.



回答4:

    String time = "06/27/2012 09:00";
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    Date date = sdf.parse(time);
    System.out.println("TIME BEFORE PARSE: " + time);
    System.out.println("TIME AFTER PARSE : " + date);

In your example date format is wrong. You have give "dd/MM/yyyy HH:mm" which should be "MM/dd/yyyy HH:mm"



回答5:

You have used the pattern dd/MM/YYYY , but you have entered the date as MM/dd/YYYY, causing you this weird behaviour..