[英]Convert java.time.LocalDate to java.util.Date
I have java.time.LocalDate Object in yyyy-MM-dd format. 我有yyyy-MM-dd格式的java.time.LocalDate对象。 I would like to know how to convert this to java.util.Date with MM-dd-yyyy format.
我想知道如何将其转换为MM-dd-yyyy格式的java.util.Date。 getStartDate() method should be able to return Date type object with the format MM-dd-yyyy.
getStartDate()方法应该能够返回格式为MM-dd-yyyy的Date类型的对象。
DateParser class 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;
}
If you have a LocalDate
which you want to convert to a Date
, use 如果您有一个要转换为
Date
的LocalDate
,请使用
LocalDate localDate = ...; Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); Date res = Date.from(instant);
source: http://blog.progs.be/542/date-to-java-time
来源: http : //blog.progs.be/542/date-to-java-time
You can then use a SimpleDateFormat
to format the Date
to whatever format you like. 然后,您可以使用
SimpleDateFormat
将Date
格式化为所需的任何格式。
You can use the SimpleDateFormat to switch between LocalDate and Date objects. 您可以使用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.