如何使用java中的值创建日期对象 [英] How create Date Object with values in java
问题描述
我需要2014-02-11的日期对象。
我不能像这样直接创建它,
I need a date object for date 2014-02-11. I can't directly create it like this,
Date myDate = new Date(2014, 02, 11);
所以我在做如下,
Calendar myCalendar = new GregorianCalendar(2014, 2, 11);
Date myDate = myCalendar.getTime();
有没有什么简单的方法可以在java中创建日期对象?
Is there any easy way to create date object in java?
推荐答案
第一个Gotcha:通过一个月份可能会给你一些意想不到的:月份是零,这意味着2实际上是三月。
First Gotcha: passing in a 2 as month may give you something unexpected: month is zero-based, which means 2 is actually March.
我不知道你正在寻找什么是简单的方式,因为我觉得使用日历已经够轻松了。
I dunno what is a "easy" way that you are looking for as I feel that using Calendar is already easy enough.
记住要使用月份的正确常数:
Remember to use correct constants for month:
Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
另一种方法是使用DateFormat,我通常有一个这样的util:
Another way is to make use of DateFormat, which I usually have a util like this:
public static Date parseDate(String date) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
return null;
}
}
,以便我可以简单地写
Date myDate = parseDate("2014-02-14");
另一种替代方案我更喜欢:不要使用Java日期/日历了。切换到JODA时间或Java时间(也称为JSR310,可在JDK 8+中使用)。您可以使用 LocalDate
表示一个日期,可以通过
Yet another alternative I prefer: Don't use Java Date/Calendar anymore. Switch to JODA Time or Java Time (aka JSR310, available in JDK 8+). You can use LocalDate
to represent a date, which can be easily created by
LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);
这篇关于如何使用java中的值创建日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!