[英]How to format date string of Oct 9 2019 12:00:00:000AM to dd/MM/yyyy
I have date formatted as Oct 9 2019 12:00:00:000AM .我的日期格式为Oct 9 2019 12:00:00:000AM 。 I want to change its format to 09/10/2019 .我想将其格式更改为09/10/2019 。
So far here is what i tried:到目前为止,这是我尝试过的:
SimpleDateFormat outs= new SimpleDateFormat("dd/MM/yyyy");
String newDate= outs.format(invoiceEntity.getTidate()); // where invoiceEntitygetTidate() is the date
But i get error但我得到错误
*java.lang.IllegalArgumentException: *java.lang.IllegalArgumentException:
Cannot format given Object as a Date*.无法将给定的 Object 格式化为日期*。
Use Java 8 date time API, you can parse the input string into LocalDate
using DateTimeFormatter
and then parse it to required format string使用 Java 8 日期时间 API,您可以使用DateTimeFormatter
将输入字符串解析为LocalDate
,然后将其解析为所需的格式字符串
String date = "Oct 9 2019 12:00:00:000AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm:ss:SSSa");
LocalDate local = LocalDate.parse(date,formatter);
System.out.println(local.format(DateTimeFormatter.ofPattern("dd/MM/yyy")));
Or if you have java.util.Date
object, convert to java.time classes (specifically, Instant
) and proceed to get your LocalDate
object. Or if you have java.util.Date
object, convert to java.time classes (specifically, Instant
) and proceed to get your LocalDate
object.
Date utilDate = new Date();
String output = utilDate.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate()
.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(output);
Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar. Java 8 引入了新的日期和时间 API,以解决旧版 java.util.Date 和 java.util.Calendar 的缺点
Issues with the Existing Date/Time APIs现有日期/时间 API 的问题
Fr more idea please refer here更多想法请参考这里
You can use the JAVA 8 Date API feature for converting the date.您可以使用JAVA 8 Date API功能来转换日期。 Example is given below.下面给出示例。
String oldDate = "Oct 9 2019 12:00:00:000AM";
// mentioning the input date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm:ss:SSSa");
//converting the date
LocalDate localDate = LocalDate.parse(oldDate,formatter);
//Final date formatted
String formattedDate=localDate.format(DateTimeFormatter.ofPattern("dd/MM/yyy"));
System.out.println("Old Date :- "+ oldDate);
System.out.println("New Date :- "+formattedDate);
Output Output
Old Date:- Oct 9 2019 12:00:00:000AM旧日期:- 2019 年 10 月 9 日 12:00:00:000AM
New Date:- 09/10/2019新日期:- 09/10/2019
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.