简体   繁体   English

将Java中的java.util.date默认格式转换为Timestamp

[英]Convert java.util.date default format to Timestamp in Java

The default format of java.util.date is something like this "Mon May 27 11:46:15 IST 2013". java.util.date的默认格式类似于“ IST 2013年5月27日星期一11:46:15”。 How can I convert this into timestamp and calculate in seconds the difference between the same and current time? 如何将其转换为时间戳并以秒为单位计算相同时间与当前时间之间的时差?

java.util.Date date= new java.util.Date();
Timestamp ts_now = new Timestamp(date.getTime());

The above code gives me the current timestamp. 上面的代码为我提供了当前时间戳。 However, I got no clue how to find the timestamp of the above string. 但是,我不知道如何找到上述字符串的时间戳。

You can use the Calendar class to convert Date 您可以使用Calendar类转换Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

Best one 最好的

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

You can use 您可以使用

  long startTime = date.getTime() * 1000000;;
  long estimatedTime = System.nanoTime() - startTime;

To get time in nano. 在纳米中获得时间。

Java Docs Java文档

You can use DateFormat (java.text.*) to parse the date: 您可以使用DateFormat (java.text。*)来解析日期:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")

You will have to change the locale to match your own (with this you will get 10:46:15). 您将不得不更改语言环境以匹配您自己的语言环境(由此您将获得10:46:15)。 Then you can use the same code you have to convert it to a timestamp. 然后,您可以使用相同的代码将其转换为时间戳。

java.time java.time

I am providing the modern answer. 我正在提供现代答案。 The Timestamp class was always poorly designed, a real hack on top of the already poorly designed Date class. Timestamp类的设计始终很差,这是在已经设计不良的Date类之上的一个真正的技巧。 Both those classes are now long outdated. 这两个类现在早已过时。 Don't use them. 不要使用它们。

When the question was asked, you would need a Timestamp for sending a point in time to the SQL database. 提出问题时,您需要一个Timestamp来将时间点发送到SQL数据库。 Since JDBC 4.2 that is no longer the case. 从JDBC 4.2开始,情况不再如此。 Assuming your database needs a timestamp with time zone (recommended for true timestamps), pass it an OffsetDateTime . 假设您的数据库需要timestamp with time zonetimestamp with time zone (建议使用真实时间戳),则将其传递给OffsetDateTime

Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013 : the time zone abbreviation. 在执行此操作之前,我们需要克服使用示例字符串的真正麻烦, Mon May 27 11:46:15 IST 2013Mon May 27 11:46:15 IST 2013 :时区缩写。 IST may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing. IST可能表示爱尔兰的夏令时,以色列的标准时间或印度的标准时间(我什至已经读过Java可能将其解析为大西洋/雷克雅未克时区-冰岛标准时间?)为了控制解释,我们将首选时区传递给格式化程序,我们正在使用解析。

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("EEE MMM dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
            .appendPattern(" yyyy")
            .toFormatter(Locale.ROOT);
    String dateString = "Mon May 27 11:46:15 IST 2013";
    OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
            .atOffset(ZoneOffset.UTC);
    System.out.println(dateTime);

This snippet prints: 此代码段打印:

2013-05-27T06:16:15Z 2013-05-27T06:16:15Z

This is the UTC equivalent of your string (assuming IST was for India Standard Time). 这是您的字符串的UTC等效项(假设IST适用于印度标准时间)。 Pass the OffsetDateTime to your database using one of the PreparedStatement.setObject methods (not setTimestamp ). 使用PreparedStatement.setObject方法之一(而不是setTimestamp )将OffsetDateTime传递到数据库。

How can I convert this into timestamp and calculate in seconds the difference between the same and current time? 如何将其转换为时间戳并以秒为单位计算相同时间与当前时间之间的时差?

Calculating the difference in seconds goes very naturally with java.time: 用java.time很自然地计算出以秒为单位的差异:

    long differenceInSeconds = ChronoUnit.SECONDS
            .between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
    System.out.println(differenceInSeconds);

When running just now I got: 刚运行时,我得到:

202213260 202213260

Link: Oracle tutorial: Date Time explaining how to use java.time. 链接: Oracle教程:Date Time说明如何使用java.time。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM