在一行中设置日期

发布于 2024-09-02 21:25:51 字数 324 浏览 1 评论 0 原文

根据 Java API,构造函数 Date(year,month,day) 已弃用。我知道我可以用以下代码替换它:

Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear);
myCal.set(Calendar.MONTH, theMonth);
myCal.set(Calendar.DAY_OF_MONTH, theDay);
Date theDate = myCal.getTime();

但是,我想要更短的代码来替换它(最好是一到两行)。

According to the Java API, the constructor Date(year, month, day) is deprecated. I know that I can replace it with the following code:

Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear);
myCal.set(Calendar.MONTH, theMonth);
myCal.set(Calendar.DAY_OF_MONTH, theDay);
Date theDate = myCal.getTime();

However, I would like something shorter to replace it with (ideally one to two lines).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

深海少女心 2024-09-09 21:25:51

您可以使用 new GregorianCalendar(theYear, theMonth, theDay).getTime()

public GregorianCalendar(int 年,int 月,int dayOfMonth)

构造一个 GregorianCalendar,其给定日期设置在默认时区和默认语言环境中。

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

祁梦 2024-09-09 21:25:51

你可以使用

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )

You could use

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )
老子叫无熙 2024-09-09 21:25:51

这是使用乔达时间

new DateMidnight(2010, 3, 5)

DateMidnight 现已弃用,但使用 Joda Time DateTime 可以达到相同的效果

DateTime dt = new DateTime(2010, 3, 5, 0, 0);

This is yet another reason to use Joda Time

new DateMidnight(2010, 3, 5)

DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime

DateTime dt = new DateTime(2010, 3, 5, 0, 0);
我的黑色迷你裙 2024-09-09 21:25:51

日历有一个 set() 方法,可以在一次调用中设置年、月和日期:

myCal.set( theYear, theMonth, theDay );

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );
笑饮青盏花 2024-09-09 21:25:51

为什么不编写一个简单的实用方法:

public final class DateUtils {
    private DateUtils() {
    }

    public static Calendar calendarFor(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        return cal;
    }

    // ... maybe other utility methods
}

然后在其余代码中的任何地方调用它:

Calendar cal = DateUtils.calendarFor(2010, Calendar.MAY, 21);

Why don't you just write a simple utility method:

public final class DateUtils {
    private DateUtils() {
    }

    public static Calendar calendarFor(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        return cal;
    }

    // ... maybe other utility methods
}

And then call that everywhere in the rest of your code:

Calendar cal = DateUtils.calendarFor(2010, Calendar.MAY, 21);
紙鸢 2024-09-09 21:25:51

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…或…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

Java 8 中内置的 java.time 框架后来取代了麻烦的旧类 java.util.Date/.Calendar。

java.time 类使用不可变对象。所以它们本质上是线程安全的。您将不会遇到其他答案中提到的线程安全问题。

LocalDate

该框架包含一个用于仅日期对象的类,没有任何时间或时区,LocalDate。请注意,确定日期需要时区 (ZoneId)。

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

您可以实例化特定日期。请注意,与旧类不同,月份数是 1-12 的合理范围。

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

或者使用枚举 Month

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

转换

Best 以避免旧的日期时间类。但如果你必须的话,你可以转换。调用旧类中添加的新方法以方便转换。

在这种情况下,我们需要指定一个时间与我们的仅日期值一起使用,以组合为 java.util.Date 对象。一天中的第一时刻可能是有道理的。让 java.time 确定第一个时刻的时间,因为它并不总是 00:00:00.0

我们还需要指定时区,因为日期因时区而异。

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

Instant 是 java.time 中的一个基本类,表示 UTC 时间轴上的一个时刻。将 Instant 提供给 Date 上的静态方法进行转换。

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 /jeps/170" rel="nofollow noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time 。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…or…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.

The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.

LocalDate

This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId) is necessary to determine a date.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

Or use the enum, Month.

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

Convert

Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.

In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0.

We also need to specify a time zone, as the date varies by time zone.

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

An Instant is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant to static method on Date to convert.

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

潜移默化 2024-09-09 21:25:51

在 Java 8 中使用构造函数 Date(year,month,date) 已被弃用:

Date date = new Date(1990, 10, 26, 0, 0);

最好的方法是使用 SimpleDateFormat

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");

你需要导入 import java.text .SimpleDateFormat;

Use the constructor Date(year,month,date) in Java 8 it is deprecated:

Date date = new Date(1990, 10, 26, 0, 0);

The best way is to use SimpleDateFormat

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");

you need to import import java.text.SimpleDateFormat;

等风也等你 2024-09-09 21:25:51
Date date = new DateTime(2014, 6, 20, 0, 0).toDate();

DateTime 来自 Joda.org https://www. joda.org/joda-time/apidocs/org/joda/time/DateTime.html

Date date = new DateTime(2014, 6, 20, 0, 0).toDate();

DateTime is from Joda.org https://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文