Taher Ali
Taher Ali

Reputation: 37

How to convert timestamp date to java.util date(yyyy-mm-dd) in java

I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.
Any help on this would be really appreciated

Upvotes: 0

Views: 13141

Answers (3)

deHaar
deHaar

Reputation: 18568

You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:

public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
    // convert it to a modern date object
    LocalDate justDate = ts.toLocalDateTime().toLocalDate();
    // print it using a suitable formatter
    System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

The output (today) is

2020-02-17

You just need Java 8 or higher for this or import a backport library.

EDIT

If you don't need a String but a java.util.Date, do it with Instant only, like this:

public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    Instant now = Instant.now();
    Timestamp ts = Timestamp.from(now);
    // create an Instant from the Timestamp
    Instant timestampInstant = ts.toInstant();
    // and then create a Date out from that Instant
    java.util.Date creationDate = java.util.Date.from(now);

    // do something with the Date here...
}

But please consider using java.time wherever possible, which might be in your domain class...

Upvotes: 2

Adrian Lagartera
Adrian Lagartera

Reputation: 506

That question is answered here

And what you want exactly, to display the date with that format or save with that format.

If you want display the date with (yyyy-mm-dd)

String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);

If you want save the date with that format you can try to do this:

try {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
     String dateFormated = dateFormat.format(myTimestamp);
     Date parsedDate = dateFormat.parse(dateFormated);
     Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) { 

}

Upvotes: 0

Sriram Umapthy
Sriram Umapthy

Reputation: 700

 private String  getZonedDateTime(String startTime){
  // input -> startTime: 2020-02-17T09:40:37.850+0000
  // output -> 2020-02-17
  return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
 }

Just pass the Date String which you have and get it in what format you want.

Upvotes: 1

Related Questions