I have java.time.LocalDate Object in yyyy-MM-dd format. I would like to know how to convert this to java.util.Date with MM-dd-yyyy format. getStartDate() method should be able to return Date type object with the format MM-dd-yyyy.
DateParser class
package com.accenture.javadojo.orgchart;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;
public class DateParser {
public static LocalDate parseDate(String strDate){
try{
if((strDate != null) && !("").equals(strDate)){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy").withLocale(Locale.US);
LocalDate date = LocalDate.parse(strDate, formatter);
return date;
}
} catch (DateTimeParseException e) {
e.printStackTrace();
}
return null;
}
}
public Date getStartDate() {
String fmd = format.format(startDate);
LocalDate localDate = DateParser.parseDate(fmd);
return startDate;
}
If you have a LocalDate
which you want to convert to a Date
, use
LocalDate localDate = ...; Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); Date res = Date.from(instant);
You can then use a SimpleDateFormat
to format the Date
to whatever format you like.
You can use the SimpleDateFormat to switch between LocalDate and Date objects.
import java.text.SimpleDateFormat;
public Date getStartDate() {
String fmd = format.format(startDate);
LocalDate localDate = DateParser.parseDate(fmd);
SimpleDateFormat actual = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat wanted = new SimpleDateFormat("MM-dd-yyyy");
String reformatted = wanted.format(actual.parse(localDate.toString()));
Date date = wanted.parse(reformatted);
return date;
}
来源:https://stackoverflow.com/questions/30651019/convert-java-time-localdate-to-java-util-date