-1

I currently have an API that returns a date in this format:

1607474368095

But I need it to be in format dd-MM-yyyy HH:mm:ss

I have tried to parse with a LocalDateTimebut it fails.

I try to do a getDate() but it tells me that it is deprecated.

Right now, I don't know of any way to parse a given date in this format.

user11804298
  • 80
  • 1
  • 12
  • 2
    probably related to https://stackoverflow.com/questions/35183146/how-can-i-create-a-java-8-localdate-from-a-long-epoch-time-in-milliseconds – Iłya Bursov Sep 01 '21 at 13:26

2 Answers2

1

The provided date is in unix timestamp. Here you first need to do 2 things:

a) Convert it to date
b) Parse it to required format

public class MyDateFormatter {

 public static final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

 public String formatDate(String date) {
  return dateFormat.format(new java.util.Date((Long.valueOf(date))))
 }

}

Test results:

Input : 1607474368095

Output : 09-12-2020 06:09:28

Gaurav Jeswani
  • 4,134
  • 6
  • 23
  • 41
  • 1
    Indeed, this answer is valid, it does the formatting as I need and I thank you for the contribution. – user11804298 Sep 01 '21 at 14:41
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Sep 01 '21 at 19:33
  • I take into account everything you comment. I do use Java 1.8 version, but if I ever use a higher version, then I will follow the other recommendations. – user11804298 Sep 03 '21 at 16:07
  • `DateTimeFormatter` and java.time were introduced in Java 8. There are some minor improvements in Java 9. – Ole V.V. Sep 03 '21 at 16:23
0

Just use DateFormat class in its SimpleDateFormat implementation:

Date date = new Date(1607474368095); // <- use your UNIX timestamp as Date constructor parameter
public final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.format(date);
Frighi
  • 464
  • 4
  • 17