This question already has an answer here:
I Have the following code in my application
System.out.println(rec.getDateTrami().getTime());
I need to convert the following format (I suppose that they are seconds)
43782000
29382000
29382000
To a format YYYY-MM-DD HH24:MI:SS
, anyone can help to me?
You could use SimpledateFormat.
Use
java.time
Best if you can change
getDateTrami()
to return anOffsetDateTime
orZonedDateTime
fromjava.time
.java.time
is the modern Java date and time API. It is also known as JSR-310. The code is the same no matter which of the two mentioned types is returned:This prints a date and time like
java.time
is generally so much nicer to work with than the outmodedDate
class and its friends.If you cannot change the return type
I assume
getDateTrami()
returns ajava.util.Date
. Since theDate
class is long outmoded, the first thing to do is to convert it tojava.time.Instant
. From there you perform your further operations:The result is similar to the above, of course. I on purpose made explicit in which time zone I want to interpret the point in time. Please substitute your own if it doesn’t happen to be Atlantic/Cape_Verde.
Formatting seconds since the epoch
This snippet prints
A date in December 1970. If this is incorrect, it is because 29 382 000 didn’t denote seconds since the epoch of January 1, 1970 at midnight in UTC, also known as the Unix epoch. This is by far the most common time to measure seconds from. If your seconds are measured from some other fixed point in time, I cannot guess which, and you have got a job to do to find out. Again decide which time zone you want to specify.
You can make use of the
SimpleDateFormat
Example:
Documentation: SimpleDateFormat, DateFormat