【发布时间】:2020-06-09 23:51:47
【问题描述】:
/*I want the same Date of my String has
Tried with couple of options but nothing worked
pasting some of code here */
public void stringToDate() {
//Current format "13-FEB-20 03.21.08.100000000 PM" in Melbourne Timezone
//Required Format yyyy-dd-MM HH:mm:ss.SSS in Melbourne Timezone
String inputAM = "13-FEB-20 03.21.08.100000000 PM";
try {
DateFormat df1 = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
Date d1 = df1.parse(inputAM);
System.out.println("Date-1: " + d1); //Fri Feb 14 19:07:48 AEDT 2020
DateFormat df2 = new SimpleDateFormat("DD-MMM-yy hh.mm.ss.S aa");
Date d2 = df2.parse(inputAM);
System.out.println("Date-2: " + d2); //Tue Jan 14 19:07:48 AEDT 2020
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat etDf = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss.SSS");
TimeZone etTimeZone = TimeZone.getTimeZone("Australia/Melbourne");
etDf.setTimeZone(etTimeZone);
DateFormat df3 = new SimpleDateFormat("dd-MMM-yy HH.mm.ss.SSSSSSSSS a");
Date d3;
try {
d3 = df3.parse(inputAM);
System.out.println("Date-3: " + d3); //Fri Feb 14 07:07:48 AEDT 2020
System.out.println("Date-4: " + etDf.format(d3.getTime())); //2020-14-02 07:07:48.000
} catch (ParseException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDateTime和DateTimeFormatter。
标签: java java-8 simpledateformat localdate