Parsing Java String to date

2019-07-24 15:16发布

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?

5条回答
戒情不戒烟
2楼-- · 2019-07-24 15:38

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-07-24 15:53
    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"

查看更多
唯我独甜
4楼-- · 2019-07-24 15:54

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.

查看更多
Anthone
5楼-- · 2019-07-24 15:54

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

查看更多
Luminary・发光体
6楼-- · 2019-07-24 15:55

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.)

查看更多
登录 后发表回答