Java 在一行中设置日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2877532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Date in a single line
提问by hibernate
According to the Java API, the constructor Date(year, month, day)
is deprecated. I know that I can replace it with the following code:
根据 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();
However, I would like something shorter to replace it with (ideally one to two lines).
但是,我想要更短的东西来代替它(最好是一到两行)。
采纳答案by aioobe
You could use new GregorianCalendar(theYear, theMonth, theDay)
.getTime()
:
你可以使用: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.
public GregorianCalendar(int year, int month, int dayOfMonth)
使用默认语言环境在默认时区中设置给定日期,构造一个 GregorianCalendar。
回答by Sean Owen
This is yet another reason to use Joda Time
这是使用Joda Time 的另一个原因
new DateMidnight(2010, 3, 5)
DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime
DateMidnight 现在已弃用,但使用 Joda Time 可以实现相同的效果 DateTime
DateTime dt = new DateTime(2010, 3, 5, 0, 0);
回答by tangens
You could use
你可以用
new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )
回答by martin clayton
回答by Jesper
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);
回答by Cheng
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
DateTime 来自 Joda.org https://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html
回答by Basil Bourque
tl;dr
tl;博士
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.
Java 8 及更高版本中内置的 java.time 框架取代了麻烦的旧类 java.util.Date/.Calendar。
The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safetyproblems mentioned on the other answers.
java.time 类使用不可变对象。所以它们本质上是线程安全的。您将不会遇到其他答案中提到的任何线程安全问题。
LocalDate
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
. 请注意,时区 ( ZoneId
) 是确定日期所必需的。
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.
您可以实例化特定日期。请注意,与旧类不同,月份数是 1-12 的合理范围。
LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );
Or use the enum, Month
.
或者使用枚举,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
.
在这种情况下,我们需要指定一个时间与我们的仅日期值一起使用,以组合为一个java.util.Date
对象。一天中的第一个时刻可能是有道理的。让 java.time 确定第一时刻的时间,因为它并非总是如此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.
AnInstant
是 java.time 中的一个基本类,代表 UTC 时间线上的一个时刻。Instant
在 Date 上提供一个to 静态方法以进行转换。
Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11和更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- 更高版本的 Android 捆绑实现java.time类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject 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.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by GAbriel lopez
Use the constructor Date(year,month,date)
in Java 8 it is deprecated:
Date(year,month,date)
不推荐使用 Java 8 中的构造函数:
Date date = new Date(1990, 10, 26, 0, 0);
The best way is to use SimpleDateFormat
最好的方法是使用 SimpleDateFormat
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");
you need to import import java.text.SimpleDateFormat;
你需要导入 import java.text.SimpleDateFormat;