如何在Java中以字符串格式获取当前时间戳?“yyyy.MM.dd.HH.mm.ss”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23068676/
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
How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
提问by user3388884
How to get timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
如何在Java中以字符串格式获取时间戳?“yyyy.MM.dd.HH.mm.ss”
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Timestamp());
This is what I have, but Timestamp() requires an parameters...
这就是我所拥有的,但是 Timestamp() 需要一个参数...
采纳答案by Jigar Joshi
回答by dimoniy
Use java.util.Date
class instead of Timestamp.
使用java.util.Date
类而不是时间戳。
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
This will get you the current date in the format specified.
这将为您提供指定格式的当前日期。
回答by Kakarot
You can make use of java.util.Date instead of Timestamp :
您可以使用 java.util.Date 而不是 Timestamp :
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
回答by user3144836
A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)
更合适的方法是在构造函数中指定 Locale 区域作为参数。下面的示例使用美国语言环境区域。日期格式对区域设置敏感,并使用区域设置来定制与用户所在区域区域设置 (Java Platform SE 7)的习俗和约定相关的信息
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());
回答by Basil Bourque
tl;dr
tl;博士
Use only modern java.timeclasses. Never use the terrible legacy classes such as SimpleDateFormat
, Date
, or java.sql.Timestamp
.
仅使用现代java.time类。永远不要使用糟糕的遗留类,例如SimpleDateFormat
, Date
, 或java.sql.Timestamp
。
ZonedDateTime // Represent a moment as perceived in the wall-clock time used by the people of a particular region ( a time zone).
.now( // Capture the current moment.
ZoneId.of( "Africa/Tunis" ) // Specify the time zone using proper Continent/Region name. Never use 3-4 character pseudo-zones such as PDT, EST, IST.
) // Returns a `ZonedDateTime` object.
.format( // Generate a `String` object containing text representing the value of our date-time object.
DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" )
) // Returns a `String`.
Or use the JVM's current default time zone.
或者使用 JVM 的当前默认时区。
ZonedDateTime
.now( ZoneId.systemDefault() )
.format( DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" ) )
java.time& JDBC 4.2
java.time& JDBC 4.2
The modern approach uses the java.timeclasses as seen above.
现代方法使用java.time类,如上所示。
If your JDBC driver complies with JDBC 4.2, you can directly exchange java.timeobjects with the database. Use PreparedStatement::setObject
and ResultSet::getObject
.
如果您的 JDBC 驱动程序符合 JDBC 4.2,您可以直接与数据库交换java.time对象。使用PreparedStatement::setObject
和ResultSet::getObject
。
Use java.sql only for drivers before JDBC 4.2
仅对 JDBC 4.2 之前的驱动程序使用 java.sql
If your JDBC driver does not yet comply with JDBC 4.2 for support of java.timetypes, you must fall back to using the java.sql classes.
如果您的 JDBC 驱动程序不符合 JDBC 4.2 以支持java.time类型,您必须回退到使用 java.sql 类。
Storing data.
存储数据。
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , odt ) ;
Retrieving data.
检索数据。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
The java.sql types, such as java.sql.Timestamp
, should only be used for transfer in and out of the database. Immediately convert to java.time types in Java 8 and later.
java.sql 类型,例如java.sql.Timestamp
,应该只用于传入和传出数据库。在 Java 8 及更高版本中立即转换为 java.time 类型。
java.time.Instant
java.time.Instant
A java.sql.Timestamp
maps to a java.time.Instant
, a moment on the timeline in UTC.
Ajava.sql.Timestamp
映射到java.time.Instant
UTC 时间线上的一个时刻。
java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant();
Time Zone
时区
Apply the desired/expected time zone to get a ZonedDateTime
.
应用所需/预期的时区以获取ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Formatted Strings
格式化字符串
Use a DateTimeFormatter
to generate your string. The pattern codes are similar to those of java.text.SimpleDateFormat
but not exactly, so read the doc carefully.
使用 aDateTimeFormatter
生成您的字符串。模式代码类似于java.text.SimpleDateFormat
但不完全相同,因此请仔细阅读文档。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" );
String output = zdt.format( formatter );
This particular format is ambiguous as to its exact meaning as it lacks any indication of offset-from-UTCor time zone.
这种特殊格式的确切含义是不明确的,因为它没有任何从 UTC或时区偏移的指示。
ISO 8601
ISO 8601
If you have any say in the matter, I suggest you consider using standard ISO 8601formats rather than rolling your own. The standard format is quite similar to yours. For example:2016-02-20T03:26:32+05:30
.
如果您对此事有任何发言权,我建议您考虑使用标准ISO 8601格式,而不是使用自己的格式。标准格式与您的非常相似。例如:2016-02-20T03:26:32+05:30
。
The java.time classes use these standard formats by default, so no need to specify a pattern. The ZonedDateTime
class extends the standard format by appending the name of the time zone (a wise improvement).
java.time 类默认使用这些标准格式,因此无需指定模式。该ZonedDateTime
班通过附加的时区的名称(一个明智的改进)扩展的标准格式。
String output = zdt.toString(); // Example: 2007-12-03T10:15:30+01:00[Europe/Paris]
Convert to java.sql
转换为 java.sql
You can convert from java.time back to java.sql.Timestamp
. Extract an Instant
from the ZonedDateTime
.
您可以从 java.time 转换回java.sql.Timestamp
. 提取Instant
自ZonedDateTime
。
New methods have been added to the old classes to facilitate converting to/from java.time classes.
新方法已添加到旧类中,以方便与 java.time 类之间的转换。
java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );
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 Phoenix
You can use the following
您可以使用以下
new java.sql.Timestamp(System.currentTimeMillis()).getTime()
Result : 1539594988651
Hope this will help. Just my suggestion and not for reward points.
希望这会有所帮助。只是我的建议,而不是奖励积分。
回答by gzc
Use modern java.time
classes if you use java 8 or newer.
java.time
如果您使用 java 8 或更新版本,请使用现代类。
String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat
.
Basil Bourque的回答非常好。但是时间太长了。许多人没有耐心阅读它。前 3 个答案太旧了,可能会误导 Java new bee。所以我为新来的开发人员提供了这个简短而现代的答案。希望这个答案可以减少可怕的SimpleDateFormat
.