Java 时间戳 - 如何创建日期为 23/09/2007 的时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/974973/
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
Java Timestamp - How can I create a Timestamp with the date 23/09/2007?
提问by pigouina
How can I create a Timestamp with the date 23/09/2007?
如何创建日期为 23/09/2007 的时间戳?
采纳答案by Adam Paynter
By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a longargument. You can parse this using the DateFormatclass:
通过Timestamp,我相信你的意思java.sql.Timestamp。你会注意到这个类有一个接受long参数的构造函数。您可以使用DateFormat该类解析它:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
回答by Philipp
According to the APIthe constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendarimplementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillismethod.
根据API,不推荐接受年、月等的构造函数。相反,您应该使用接受 long 的构造函数。您可以使用Calendar实现来构造您想要的日期并将时间表示访问为 long,例如使用getTimeInMillis方法。
回答by Matthew Flaschen
What do you mean timestamp? If you mean milliseconds since the Unix epoch:
你是什么意思时间戳?如果你的意思是自 Unix 纪元以来的毫秒数:
GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();
If you want an actual java.sql.Timestamp object:
如果你想要一个实际的 java.sql.Timestamp 对象:
Timestamp ts = new Timestamp(millis);
回答by pigouina
What about this?
那这个呢?
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");
回答by Alex
You could also do the following:
您还可以执行以下操作:
// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());
回答by CSquid
A more general answer would be to import java.util.Date, then when you need to set a timestampequal to the current date, simply set it equal to new Date().
更一般的答案是 import java.util.Date,然后当您需要将 a 设置为timestamp等于当前日期时,只需将其设置为等于new Date()。
回答by user152468
回答by Basil Bourque
tl;dr
tl;博士
java.sql.Timestamp.from (
LocalDate.of ( 2007 , 9 , 23 )
.atStartOfDay( ZoneId.of ( "America/Montreal" ) )
.toInstant()
)
java.time
时间
Let's update this page by showing code using the java.timeframework built into Java 8 and later.
让我们通过使用Java 8 及更高版本中内置的java.time框架显示代码来更新此页面。
These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extraproject. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.
这些新类的灵感来自Joda-Time,由JSR 310定义,并由ThreeTen-Extra项目扩展。它们取代了与早期 Java 版本捆绑在一起的臭名昭著的旧日期时间类。
In java.time, an Instantis a moment on the timeline in UTC. A ZonedDateTimeis an Instant adjusted into a time zone (ZoneId).
在java.time 中,anInstant是UTC 时间线上的一个时刻。AZonedDateTime是调整到时区 ( ZoneId)的 Instant 。
Time zone is crucial here. A date of September 23, 2007cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.
时区在这里至关重要。如果September 23, 2007不应用时区,则无法将日期转换为时间轴上的某个时刻。考虑到新的一天在巴黎比在蒙特利尔更早,在那里它仍然是“昨天”。
Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0because of Daylight Saving Time and possibly other anomalies.
此外,java.sql.Timestamp 表示日期和时间。所以我们必须注入一个时间来配合日期。我们假设您希望将一天中的第一个时刻作为一天中的时间。请注意,00:00:00.0由于夏令时和可能的其他异常情况,这并不总是时间。
Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.
请注意,与旧的 java.util.Date 类和 Joda-Time 不同,java.time 类型的分辨率为纳秒而不是毫秒。这与 java.sql.Timestamp 的分辨率相匹配。
Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM's current default time zone to its date-time value when generating a string representation via its toStringmethod. Here you see my America/Los_Angelestime zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601formats.
请注意, java.sql.Timestamp 有一个坏习惯,即在通过其toString方法生成字符串表示时隐式地将 JVM 的当前默认时区应用于其日期时间值。在这里您可以看到我America/Los_Angeles应用的时区。相比之下,java.time 类更加理智,使用标准ISO 8601格式。
LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;
Dump to console.
转储到控制台。
System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );
When run.
跑的时候。
d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0
d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[美国/蒙特利尔] = 即时:2007-09-23T04:00:00Z = ts: 2007-09-22: 21:00 00.0
By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp.
顺便说一下,从 JDBC 4.2 开始,您可以直接使用 java.time 类型。不需要java.sql.Timestamp。
PreparedStatement.setObjectResultSet.getObject
PreparedStatement.setObjectResultSet.getObject
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 。
- 安卓
- java.time类的更高版本的 Android 捆绑实现。
- 对于早期的 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,和更多。

