格式化日期字符串以删除JAVA中的时间

dsi*_*dsi 1 java string date

示例,字符串值为:

15/08/2013 15:30 GMT+10:00 
Run Code Online (Sandbox Code Playgroud)

我想15/08/2013在Java 上格式化上面的字符串(删除时间部分,只保留日期).

我该怎么做这种格式?

Sur*_*tta 6

删除时间部分,只保留日期

String dateString= "15/08/2013 15:30 GMT+10:00";
String result  = dateString.split(" ")[0];
Run Code Online (Sandbox Code Playgroud)

那给了你 15/08/2013

我猜,没有必要格式化.


Mad*_*mer 5

2018年

由于现在是 2018 年,而且我们在 Java 8+(和ThreeTen Backport)中有日期/时间 API ,你可以做一些类似的事情......

String text = "15/08/2013 15:30 GMT+10:00";
LocalDateTime ldt = LocalDateTime.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm z", Locale.ENGLISH));
System.out.println(ldt);

// In case you just want to do some "date" manipulation, without the time component
LocalDate ld = ldt.toLocalDate();
// Will produce "2013-08-15"
//String format = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE);
String format = ldt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(format);
Run Code Online (Sandbox Code Playgroud)

原答案

一种方法是将String日期解析为Date对象,然后根据您的要求简单地格式化

String text = "15/08/2013 15:30 GMT+10:00";
SimpleDateFormat inFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm z");
Date date = inFormat.parse(text);
System.out.println(date);

SimpleDateFormat outFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatted = outFormat.format(date);
System.out.println(formatted);
Run Code Online (Sandbox Code Playgroud)

Date如果您需要它用于其他事情,这具有保留日期/时间信息的好处;)

请参阅,SimpleDateFormat了解更多详情