0

I am trying to convert the following string (Input: 2020-06-01-02.55.44.258554) to timestamp. I cannot use simpledateformatwith the following format yyyy-MM-dd-HH.mm.ss.SSSSSS because it gives this result (2020-06-01-03.00.02.000554) which is not correct.

How do I do it ?

CODE FOR YOUR REFERENCE :

        String oldPattern = "yyyy-MM-dd-HH.mm.ss.SSSSSS", newPattern = "yyyy-MM-dd-HH.mm.ss.SSSSSS";
        SimpleDateFormat sdf = new SimpleDateFormat(oldPattern);
        
        Date date = sdf.parse("2020-06-01-02.55.44.258554");
        sdf.applyPattern(newPattern);
        String NEWDATE = sdf.format(date).toUpperCase();
test dummy
  • 81
  • 4
  • 11
  • 1
    `java.util.Date` only has a precision of milliseconds, not microseconds. I suggest you use `java.time.Instant` instead, which has nanosecond precision. – Jon Skeet Jul 31 '20 at 17:45
  • 1
    @JonSkeet Why not localdatetime ? – test dummy Jul 31 '20 at 17:55
  • Your subject talks about a timestamp, which is normally represented as an Instant rather than LocalDateTime. We don't really know what your value is meant to represent... but if it's genuinely a timestamp generated by a machine, Instant is probably most appropriate. – Jon Skeet Jul 31 '20 at 17:56
  • Yes, it is a timestamp. Thank you. Is instant affected by zone ? – test dummy Jul 31 '20 at 17:58
  • I would suggest reading the documentation - that's a question which isn't directly related to what you're asking in the post. – Jon Skeet Jul 31 '20 at 18:00
  • I read some things: https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime#:~:text=Instant%20and%20LocalDateTime%20are%20two,class%20cannot%20represent%20a%20moment. – test dummy Jul 31 '20 at 18:00
  • This question was very helpful. It says that Instant is an instant in UTC, whereas LocalDateTime is not affected by zone. I don't want my timestamp, which is an incoming string parameter to be converted to a different timezone with insttant. What should I do ? – test dummy Jul 31 '20 at 18:01
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` (or `Instant`, as discussed) and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 31 '20 at 18:02
  • 1
    What do you mean by "converted to a different time zone"? What time zone *is* the incoming value in? The value you've shown doesn't have any indication of a time zone or UTC offset, which makes it somewhat unhelpful as a timestamp. – Jon Skeet Jul 31 '20 at 18:03

0 Answers0