【问题标题】:Convert java.time.LocalDate to java.util.Date将 java.time.LocalDate 转换为 java.util.Date
【发布时间】: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-yyyyDate 对象只是一个时间戳。它没有格式。如果您想要一种格式,请使用 SimpleDateFormatformat Date
  • @SotiriosDelimanolis 如果您检查下面的 getStartDate() 方法,您会看到我有 LocalDate 对象。但是方法返回的是 Date 类型的对象。所以我想做的是,将 localDate 对象转换为 util Date 对象。

标签: java simpledateformat java.util.date


【解决方案1】:

如果您有一个 LocalDate 想要转换为 Date,请使用

LocalDate localDate = ...;
Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

来源:http://blog.progs.be/542/date-to-java-time

然后您可以使用SimpleDateFormatDate 格式化为您喜欢的任何格式。

【讨论】:

    【解决方案2】:

    您可以使用 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;
        }
    

    【讨论】:

    • 感谢您的回复。但它没有用。我打印了 localDate,它是:1907-01-01。然后我打印了“日期”,它是这样的:Tue Jan 01 00:00:00 EST 1907
    • 投反对票的原因? Date 是上面评论中@SotiriosDelimanolis 响应中提到的对象!如果您需要将其显示为具有 MM-dd-yyy 格式的格式化字符串,那么在您调用 getStartDate() 方法的地方使用类似SimpleDateFormat wanted = new SimpleDateFormat("MM-dd-yyyy"); wanted.format(date.toString());
    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2015-01-30
    • 2011-08-29
    • 2019-08-03
    相关资源
    最近更新 更多