gpt4 book ai didi

java - 如何从年月日中获取日期对象?

转载 作者:行者123 更新时间:2023-11-29 09:52:51 25 4
gpt4 key购买 nike

当我使用下面的代码时,Date 对象是错误的。

Date date = new Date(day.getYear(), day.getMonth(), day.getDay());

谁能告诉我如何从年、月、日的值中获取日期对象?

最佳答案

您可以使用 Calendar 类来实现这一点。

public static void main(String[] args) throws Exception {
Date date = new Date (115, 7, 5);
System.out.println("date = " + date);

Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 5);
calendar.set(Calendar.MONTH, 7);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
date = calendar.getTime();
System.out.println("calendar = " + date);

// or create directly a new clanedar instance
// thanks Tom to mention this
calendar = new GregorianCalendar(2015, 7, 5);
date = calendar.getTime();
System.out.println("calendar = " + date);
}

输出

date     = Wed Aug 05 00:00:00 CEST 2015
calendar = Wed Aug 05 00:00:00 CEST 2015
calendar = Wed Aug 05 00:00:00 CEST 2015

关于java - 如何从年月日中获取日期对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826713/

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