Format date in Java

2019-01-26 18:32发布

I have the following string:

Mon Sep 14 15:24:40 UTC 2009

I need to format it into a string like this:

14/9/2009

How do I do it in Java?

4条回答
仙女界的扛把子
2楼-- · 2019-01-26 18:51

One liner in java 8 and above.

String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy"));
查看更多
3楼-- · 2019-01-26 19:04
Date d = new Date("Mon Sep 14 15:24:40 UTC 2009");
SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy");
String s = new String(f.format(d));
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-26 19:07

You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object.

After getting the date object, you can format it in the way you want.

查看更多
再贱就再见
5楼-- · 2019-01-26 19:13

Use SimpleDateFormat (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy Date and use another one to format the parsed Date to a string in another pattern.

String string1 = "Mon Sep 14 15:24:40 UTC 2009";
Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1);
String string2 = new SimpleDateFormat("d/M/yyyy").format(date);
System.out.println(string2); // 14/9/2009
查看更多
登录 后发表回答