Convert java.time.LocalDate to java.util.Date

情到浓时终转凉″ 提交于 2019-12-08 03:02:17

问题


I have java.time.LocalDate Object in yyyy-MM-dd format. I would like to know how to convert this to java.util.Date with MM-dd-yyyy format. getStartDate() method should be able to return Date type object with the format MM-dd-yyyy.

DateParser class

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;
}

回答1:


If you have a LocalDate which you want to convert to a Date, use

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

You can then use a SimpleDateFormat to format the Date to whatever format you like.




回答2:


You can use the SimpleDateFormat to switch between LocalDate and Date objects.

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;
    }


来源:https://stackoverflow.com/questions/30651019/convert-java-time-localdate-to-java-util-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!