0

i have data like this one date what i got from timestamp utc are : 2020-06-29 05:31:58.153

 LocalDateTime timestampasstring = message.getHeader().getUtcTimeStamp( SendingTime.FIELD);
 Timestamp timestamp = Timestamp.from(timestampasstring.toInstant(ZoneOffset.UTC));
 System.out.println(timestamp);
 String timestampstrings = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
 String timestampstrings2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp);

i need to get timestamp number like 2020-06-29 05:31:58 and convert it become unix timestamp like this one 1593408718 how to convert it ?

yuyu kungkung
  • 137
  • 2
  • 13
  • 2
    Start with https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#getTime-- – Scary Wombat Jun 29 '20 at 06:12
  • 2
    @ScaryWombat That class should _never_ be used except in actual JDBC code. – chrylis -cautiouslyoptimistic- Jun 29 '20 at 06:34
  • `Date currentDate = new Date();` `long t = currentDate.getTime()/1000;` – Amit kumar Jun 29 '20 at 06:37
  • @chrylis-cautiouslyoptimistic- Agree, somehow with his pre-edted question I made the bad assumption that `Timestamp` is also he had. – Scary Wombat Jun 29 '20 at 06:37
  • Are you getting any error message? Any wrong result? Please quote. Also what did your search turn up? In what way was it insufficient or didn’t work? [I downvoted because research must be done to ask a good question](http://idownvotedbecau.se/noresearch/). – Ole V.V. Jun 30 '20 at 20:27
  • I recommend you don’t use `SimpleDateFormat` and `Timestamp`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. You are already using `LocalDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Just stick to classes from java.time. – Ole V.V. Jun 30 '20 at 20:29

3 Answers3

0

Having read your question, I assume your method message.getHeader().getUtcTimeStamp(SendingTime.FIELD) returns a String (not a LocalDateTime) representing a timestamp in UTC while being formatted either like 2020-06-29 05:31:58.153 or 2020-06-29 05:31:58.

Since you have (shown) differently formatted datetimes (respectively, datetimes with a different accuracy), you will have to take care of that by defining a suitable DateTimeFormatter using a pattern able to deal with optional milliseconds (yyyy-MM-dd HH:mm:ss[.SSS]).

You can use it as follows:

public static void main(String[] args) {
    // receive the result from your message, this is just an example
    String utcTimestamp = "2020-06-29 05:31:58";
    // create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
    ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
                         .atZone(ZoneId.of("UTC"));
    // then get the epoch milliseconds / unix timestamp
    long millis = zdt.toInstant().toEpochMilli();
    // and print the result
    System.out.println(zdt + " ==> " + millis + " epoch millis");
}

The output of this is, of course, different for datetimes that are only equal down to seconds:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718000 epoch millis
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718153 epoch millis

If you call long seconds = zdt.toEpochSeconds() instead of converting toInstant().toEpochMillis (and adjust the output a little) you will get the same value for both examples:

public static void main(String[] args) {
    // receive the result from your message, this is just an example
    String utcTimestamp = "2020-06-29 05:31:58.153";
    // create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
    ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
                         .atZone(ZoneId.of("UTC"));
    // then get the epoch seconds
    long seconds = zdt.toEpochSecond();
    // and print the result
    System.out.println(zdt + "\t==>\t" + seconds + " epoch seconds");
}

Output:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718 epoch seconds

If your method really returns a LocalDateTime, you could simply skip conversions and write

public static void main(String[] args) {
    LocalDateTime utcDateTime = message.getHeader().getUtcTimeStamp(SendingTime.FIELD); 
    // then get the epoch seconds
    long seconds = utcDateTime.atZone(ZoneId.of("UTC")).toEpochSecond();
    // and print the result
    System.out.println(utcDateTime + "\t==>\t" + seconds + " epoch seconds");
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • yes from my broker there is any millisecond like 2020-06-29 05:31:58.153 but i wanna save without millisecond because if i want to get price from my database i just want to check the second same as my friend – yuyu kungkung Jun 29 '20 at 06:51
  • @yuyukungkung OK, good... see the last edit as well, please... – deHaar Jun 29 '20 at 08:04
0

If your getUtcTimeStamp method is helpful enough to return a LocalDateTime, you're most of the way there. Convert to an Instant using ldt.atOffset(ZoneOffset.UTC) (your getUtcTimeStamp really should be doing this for you if it already knows it's in UTC), then just call toEpochSecond() (or toEpochMilli() if you want the milliseconds part, but you just showed whole seconds).

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

The other answers are fine. Here’s my variant. First declare a formatter for parsing:

private DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral(' ')
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .toFormatter();

Consider declaring the formatter static and/or final. With this formatter I’d do:

    String timestampAsString = "2020-06-29 05:31:58.153";
    
    OffsetDateTime dateTime = LocalDateTime
            .parse(timestampAsString, timestampFormatter)
            .atOffset(ZoneOffset.UTC);
    long unixTimestamp = dateTime.toEpochSecond();
    
    System.out.println(unixTimestamp);

Output is what you asked for:

1593408718

The nice thing about the formatter is that it accepts both 2020-06-29 05:31:58.153 and 2020-06-29 05:31:58, that is, time both with and without fraction of second, and with any fraction of from 1 up to 9 decimals. Reusing ISO_LOCAL_TIME in the formatter buys us this.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161