【发布时间】:2015-06-04 18:03:42
【问题描述】:
我有 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;
}
【问题讨论】:
-
A
Date没有格式。 -
@SotiriosDelimanolis 我没听懂你。请您再解释一下。
-
你说返回日期类型对象,格式为 MM-dd-yyyy。
Date对象只是一个时间戳。它没有格式。如果您想要一种格式,请使用SimpleDateFormat和formatDate。 -
@SotiriosDelimanolis 如果您检查下面的 getStartDate() 方法,您会看到我有 LocalDate 对象。但是方法返回的是 Date 类型的对象。所以我想做的是,将 localDate 对象转换为 util Date 对象。
标签: java simpledateformat java.util.date