简体   繁体   English

如何在Java中以字符串格式获取当前时间戳? “yyyy.MM.dd.HH.mm.ss”

[英]How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

How to get timestamp in string format in Java?如何在Java中以字符串格式获取时间戳? "yyyy.MM.dd.HH.mm.ss" “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() 需要一个参数......

Replace代替

new Timestamp();

with

new java.util.Date()

because there is no default constructor for Timestamp , or you can do it with the method:因为Timestamp没有默认构造函数,或者您可以使用以下方法:

new Timestamp(System.currentTimeMillis());

Use java.util.Date class instead of Timestamp.使用java.util.Date类而不是 Timestamp。

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());

This will get you the current date in the format specified.这将为您提供指定格式的当前日期。

tl;dr tl;博士

Use only modern java.time classes.仅使用现代java.time类。 Never use the terrible legacy classes such as SimpleDateFormat , Date , or java.sql.Timestamp .永远不要使用像SimpleDateFormatDatejava.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.time classes as seen above.现代方法使用如上所示的java.time类。

If your JDBC driver complies with JDBC 4.2 , you can directly exchange java.time objects with the database.如果您的JDBC 驱动程序符合JDBC 4.2 ,您可以直接与数据库交换java.time对象。 Use PreparedStatement::setObject and ResultSet::getObject .使用PreparedStatement::setObjectResultSet::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.time types, 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. java.sql 类型,例如java.sql.Timestamp ,应该只用于传入和传出数据库。 Immediately convert to java.time types in Java 8 and later.在 Java 8 及更高版本中立即转换为 java.time 类型。

java.time.Instant

A java.sql.Timestamp maps to a java.time.Instant , a moment on the timeline in UTC. java.sql.Timestamp映射到java.time.Instant ,即 UTC 时间线上的时刻。 Notice the new conversion method toInstant added to the old class.注意添加到旧类的新转换方法toInstant

java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant(); 

Time Zone时区

Apply the desired/expected time zone ( ZoneId ) to get a ZonedDateTime .应用所需/预期的时区 ( ZoneId ) 以获得ZonedDateTime

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Formatted Strings格式化字符串

Use a DateTimeFormatter to generate your string.使用DateTimeFormatter生成您的字符串。 The pattern codes are similar to those of java.text.SimpleDateFormat but not exactly, so read the doc carefully.模式代码与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-UTC or time zone.这种特定格式的确切含义是模棱两可的,因为它没有任何与 UTC 或时区偏移的指示。

ISO 8601 ISO 8601

If you have any say in the matter, I suggest you consider using standard ISO 8601 formats rather than rolling your own.如果您对此事有任何发言权,我建议您考虑使用标准ISO 8601格式,而不是自己滚动。 The standard format is quite similar to yours.标准格式与您的非常相似。 For example:例如:
2016-02-20T03:26:32+05:30 . 2016-02-20T03:26:32+05:30

The java.time classes use these standard formats by default, so no need to specify a pattern. java.time 类默认使用这些标准格式,因此无需指定模式。 The ZonedDateTime class extends the standard format by appending the name of the time zone (a wise improvement). 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 .您可以从 java.time 转换回java.sql.Timestamp Extract an Instant from the ZonedDateTime .ZonedDateTime中提取一个Instant

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() );

Java(传统和现代)和标准 SQL 中的日期时间类型表


About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代了麻烦的日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

You may exchange java.time objects directly with your database.您可以直接与您的数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.使用符合JDBC 4.2或更高版本的JDBC 驱动程序 No need for strings, no need for java.sql.* classes.不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes?从哪里获得 java.time 类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目通过附加类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuarter等等

您可以使用 java.util.Date 而不是 Timestamp :

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

Use modern java.time classes if you use java 8 or newer.如果您使用 java 8 或更新版本,请使用现代java.time类。

String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

Basil Bourque's answer is pretty good. Basil Bourque 的回答非常好。 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.前 3 个答案太老了,可能会误导 Java 新手。所以我为新来的开发人员提供了这个简短而现代的答案。 Hope this answer can reduce usage of terrible SimpleDateFormat .希望这个答案可以减少可怕的SimpleDateFormat的使用。

You can use the following:您可以使用以下内容:

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result:结果:

1539594988651

A more appropriate approach is to specify a Locale region as a parameter in the constructor.更合适的方法是在构造函数中指定一个 Locale 区域作为参数。 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 regionLocale (Java Platform SE 7)日期格式对区域设置敏感,并使用区域设置来定制与用户区域区域设置(Java 平台 SE 7)的习俗和约定相关的信息

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());

I am Using this我正在使用这个

String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);

If your date is like let mydate = "2022-15-06";如果你的日期就像 let mydate = "2022-15-06";

let newDate = Date.now(mydate)让 newDate = Date.now(mydate)

Now in newDate you have the current timeStamp现在在 newDate 你有当前的时间戳

Use below code to get current timestamps: 使用以下代码获取当前时间戳:

Timestamp ts = new Timestamp(date.getTime());

For reference 以供参考

How to get current timestamps in Java 如何使用Java获取当前时间戳

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) 格式化为日期(yyyy-MM-dd HH:mm:ss) - How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) 如何比较 java 格式“EEE MMM dd HH:mm:ss zzz yyyy”和“yyyy-MM-dd hh:mm:sss”的日期时间? - How to compare the datetime of format "EEE MMM dd HH:mm:ss zzz yyyy" and "yyyy-MM-dd hh:mm:sss" in java? 无法正确将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为字符串 - Cannot correctly format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to string 将java.sql.timestamp从yyyy-MM-dd hh:mm:ss转换为MM-dd-yyyy hh:mm:ss - Convert java.sql.timestamp from yyyy-MM-dd hh:mm:ss to MM-dd-yyyy hh:mm:ss Java将字符串yyyy-MM-dd HH:mm:ss转换为加拿大/东部时区的时间戳 - Java Convert String yyyy-MM-dd HH:mm:ss to timestamp of Canada/Eastern timezone Java 格式 yyyy-MM-dd'T'HH:mm:ss.SSSz 到 yyyy-mm-dd HH:mm:ss - Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss 如何验证时间戳记(yyyy-MM-dd HH:mm:ss)和(yyyy-MM-dd) - how to validate the timestamp (yyyy-MM-dd HH:mm:ss) and (yyyy-MM-dd) 以yyyy-MM-dd hh.mm.ss格式获取当前日期时间 - get current date time in yyyy-MM-dd hh.mm.ss format 如何将 dd/MM/yyyy HH:mm:ss 转换为 offsetdatetime - java - How to convert dd/MM/yyyy HH:mm:ss to offsetdatetime - java 在Java 7中将字符串日期转换为yyyy-MM-dd'T'HH:mm:ss.SSSSSS格式的字符串 - Converting string date to string in yyyy-MM-dd'T'HH:mm:ss.SSSSSS format in java 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM