[英]Convert java.time.LocalDate to java.util.Date
我有yyyy-MM-dd格式的java.time.LocalDate对象。 我想知道如何将其转换为MM-dd-yyyy格式的java.util.Date。 getStartDate()方法应该能够返回格式为MM-dd-yyyy的Date类型的对象。
DateParser类
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;
}
如果您有一个要转换为Date
的LocalDate
,请使用
LocalDate localDate = ...; Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); Date res = Date.from(instant);
然后,您可以使用SimpleDateFormat
将Date
格式化为所需的任何格式。
您可以使用SimpleDateFormat在LocalDate和Date对象之间切换。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.