在 Java 中将字符串转换为时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29535772/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:27:05  来源:igfitidea点击:

Convert String to Timestamp in Java

java

提问by fudy

Our customer will send us request including timestamp String likes : "2013-10-27T13:00:00.325234Z". I will use it to compare timestamp in oracle database.

我们的客户将向我们发送请求,包括时间戳字符串喜欢: "2013-10-27T13:00:00.325234Z"。我将使用它来比较 oracle 数据库中的时间戳。

how to convert the above String to java.sql.Timestamp?

如何将上述字符串转换为 java.sql.Timestamp?

I can convert it to Date, but Date only has the milliseconds precision.

我可以将它转换为日期,但日期只有毫秒精度。

Should keep the microseconds and timezone. thanks in advance.

应该保留微秒和时区。提前致谢。

回答by khelwood

Apart from the T in the middle and the Z at the end, you could pass it into Timestamp.valueOf(String).

除了中间的 T 和末尾的 Z 之外,您还可以将其传入Timestamp.valueOf(String).

So you could just have:

所以你可以只拥有:

String line = "2013-10-27T13:00:00.325234Z";
Timestamp ts = Timestamp.valueOf(line.replace("T"," ").replace("Z",""));

This gives a timestamp matching

这给出了时间戳匹配

2013-10-27 13:00:00.325234

回答by Ole V.V.

Java 8

爪哇 8

    String timestampString = "2013-10-27T13:00:00.325234Z";
    Instant inst = Instant.parse(timestampString);

Don't use the Timestampclass if you can avoid it. To save the timestamp from the string, just pass the Instantto your PreparedStatementusing its setObjectmethod. It requires JDBC version 4.2 or higher. You probably have that already, or you should be able to get such a driver. You may also pass the Instantto a modern JPA implementation.

Timestamp如果可以避免,请不要使用该类。要保存字符串中的时间戳,只需使用它的方法将 传递Instant给您。它需要 JDBC 4.2 或更高版本。您可能已经拥有了,或者您应该能够获得这样的驱动程序。您还可以将 传递给现代 JPA 实现。PreparedStatementsetObjectInstant

Parsing works without any explicit formatter because your string is in ISO 8601 format, the format that the modern java date and time classes parse (and also print) as their default.

解析无需任何显式格式化程序,因为您的字符串采用 ISO 8601 格式,现代 Java 日期和时间类将其解析(并打印)为默认格式。

The Timestampclass is long outdated. If you still need a Timestamp, for example for a legacy API that you cannot change or don't want to change just now, the conversion is easy:

这个Timestamp类已经过时了。如果您仍然需要一个Timestamp,例如对于您现在无法更改或不想更改的遗留 API,则转换很容易:

    Timestamp ts = Timestamp.from(Instant.parse(timestampString));

Java 6 and 7

Java 6 和 7

Add ThreeTen Backport to your project (link below). Use the following imports.

将 ThreeTen Backport 添加到您的项目中(链接如下)。使用以下导入。

import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;

Then do:

然后做:

    Instant inst = Instant.parse(timestampString);
    Timestamp ts = DateTimeUtils.toSqlTimestamp(inst);

Links

链接

回答by RealSkeptic

This is a Java 8 solution. It relies on the java.timelibrary.

这是一个 Java 8 解决方案。它依赖于java.time库。

String isoStamp = "2013-10-27T13:00:00.325234Z";
OffsetDateTime odt = OffsetDateTime.parse(
                             isoStamp,
                             DateTimeFormatter.ISO_OFFSET_DATE_TIME );

The OffsetDateTimeis a date-time object that has a precision of nanoseconds, and includes the offset from UTC. And the ISO_OFFSET_DATE_TIMEis a standard DateTimeFormatterformat, that understands the Zdesignation and sets it as offset 0 from UTC.

OffsetDateTime是具有纳秒的精度的日期时间对象,并且包括从UTC的偏移。这ISO_OFFSET_DATE_TIME是一种标准DateTimeFormatter格式,可以理解Z指定并将其设置为 UTC 的偏移量 0。

The next step is to use this in JDBC, and Oracle says in this articlethat the java.timeobjects should be used with the setObject()method (rather than setTimeStamp()). E.g.

下一步就是在 JDBC 中使用 this,Oracle 在这篇文章中java.time对象应该与setObject()方法一起使用(而不是setTimeStamp())。例如

stmt.setObject( 1, odt, JDBCType.TIMESTAMP_WITH_TIMEZONE );

Note that this may depend on the database and JDBC driver, which should, of course, be up-to-date.

请注意,这可能取决于数据库和 JDBC 驱动程序,当然,它们应该是最新的。

回答by user8283048

For me the String format was not yyyy-MM-dd HH:mm:ss.SSSSSS. So Timestamp.valueOf didn't work. So, I did like this

对我来说,字符串格式不是 yyyy-MM-dd HH:mm:ss.SSSSSS。所以 Timestamp.valueOf 不起作用。所以,我喜欢这个

String s = "2017-12-29-05.04.18.104071";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss");//Yes, it works without .SSSSSS
Timestamp ts = new Timestamp(sdf.parse(s).getTime());
ts.setNanos(Integer.valueOf(s.substring(20)) * 1000);
System.out.println(ts.toString());

回答by Sindhoo Oad

what ever format you have define it in SimpleDate format , convert it to date and then convert it to Timestamp.

您在 SimpleDate 格式中定义的任何格式,将其转换为日期,然后将其转换为时间戳。

public static Timestamp stringToTimeStamp(String strTime){
    Timestamp tempTimestamp = null;
    if(strTime!=null && !strTime.equals(""))
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd");//format of date and time you have

        Date parsedTimeStamp = null;
        try {
            parsedTimeStamp = dateFormat.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        tempTimestamp = new Timestamp(parsedTimeStamp.getTime());


    }
    return tempTimestamp;
}

回答by T.Gounelle

[with Java8] If the format is strictly specified and you want a robust solution, use java.time.DateTimeFormatterto parse the date into a java.time.LocalDateTimethat handles fraction of seconds down to the nanos and then you can create the java.sql.Timestamp:

[使用Java8]如果格式被严格指定并且您想要一个健壮的解决方案,请使用java.time.DateTimeFormatter将日期解析为一个java.time.LocalDateTime处理几分之一秒到纳米的,然后您可以创建java.sql.Timestamp

public static void main(String[] args) throws ParseException {
    String line = "2013-10-27T13:00:00.325234Z";
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
    LocalDateTime time = LocalDateTime.parse(line, dateFormat);
    Timestamp ts = Timestamp.valueOf(time);
    System.out.println(ts);
}

prints

印刷

2013-10-27 13:00:00.325234

2013-10-27 13:00:00.325234