Use java.time
Best if you can change getDateTrami()
to return an OffsetDateTime
or ZonedDateTime
from java.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:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(rec.getDateTrami().format(formatter));
This prints a date and time like
2017-12-14 16:52:20
java.time
is generally so much nicer to work with than the outmoded Date
class and its friends.
If you cannot change the return type
I assume getDateTrami()
returns a java.util.Date
. Since the Date
class is long outmoded, the first thing to do is to convert it to java.time.Instant
. From there you perform your further operations:
Date oldfashionedDateObject = rec.getDateTrami();
ZonedDateTime dateTime = oldfashionedDateObject.toInstant()
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
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
int seconds = 29_382_000;
ZonedDateTime dateTime = Instant.ofEpochSecond(seconds)
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
This snippet prints
1970-12-06 23:40:00
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.