gpt4 book ai didi

java - 将 java.time.LocalDate 转换为 java.util.Date

转载 作者:行者123 更新时间:2023-11-30 07:00:22 26 4
gpt4 key购买 nike

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

最佳答案

如果你有一个 LocalDate,你想将它转换成一个 Date,使用

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

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

关于java - 将 java.time.LocalDate 转换为 java.util.Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30651019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com