将日期格式转换为数字日期

时间:2018-04-11 13:40:39

标签: java

我有这种格式的日期:

Tue Mar 10 00:00:00 UTC 1987

它存储在对象日期中。

Object tmp = solrDoc.getFieldValue("date_from")

我想将其转换为严格的数字格式,没有小时,时区等,例如

10.03.1987

这是我到目前为止所尝试的:

DateFormat date = new SimpleDateFormat("dd.MM.yyyy");
date.format(tmp);

它返回:

 "java.text.SimpleDateFormat@7147a660"

1 个答案:

答案 0 :(得分:2)

您尝试在format上使用Object方法,但根据documentation,您需要将此方法传递给Date。因此,您实际需要做的是将原始String解析为Date,然后对其进行格式化。

例如,您可以这样做:

String tempString = String.valueOf(solrDoc.getFieldValue("date_from"));
DateFormat formatToRead = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
DateFormat formatToWrite = new SimpleDateFormat("dd.MM.yyyy");
formatToWrite.setTimeZone(TimeZone.getTimeZone("UTC"));
Date tempDate = null;
String result = null;
try {
    tempDate = formatToRead.parse(tempString);
} catch(ParseException e){
    e.printStackTrace();
}
if(tempDate != null){
    result = formatToWrite.format(tempDate);
    System.out.println(result);
}

请注意,我必须在TimeZone上设置formateToWrite才能将其保留为UTC。

如果您想了解我用于解析原始SimpleDateFormat的{​​{1}}的更多信息,请参阅this SO answer