How to convert String date to Date?

2020-05-09 18:25发布

I have done following code:

String str = "2013-01-17 11:26";
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:MM");
Date date = dateFormat.parse(str);
System.out.println("str :"+str);
System.out.println("Date :"+date);

Output

str :21-01-2013 11:26 
Date :Sat Feb 21 11:01:00 IST 2015

But something is wrong. I expect out as same as string date. i.e. Thu Jan 21 11:26:00 IST 2013

3条回答
We Are One
2楼-- · 2020-05-09 19:08

You are using the wrong format. MM is for month, and mm is for minutes, and for hours use HH. See SimpleDateFormat for various other formats.

Change your format to: -

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
查看更多
不美不萌又怎样
3楼-- · 2020-05-09 19:09

Just Using of DateFormat Class:

ateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
查看更多
唯我独甜
4楼-- · 2020-05-09 19:12

The following code should work well:

try{
String str = "2013-01-17 11:26";
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm");
Date date = (Date)dateFormat.parse(str);
System.out.println("str :"+str);
System.out.println("Date :"+date);
}
catch(Exception e){
   e.getStackTrace();
}
查看更多
登录 后发表回答