有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    您试图在Object上使用format方法,但根据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);
    }
    

    请注意,我必须在formateToWrite上设置TimeZone以保持UTC

    如果您想要更多关于我用来解析您的原始StringSimpleDateFormat的信息,请参考this SO answer