Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #98 Epoch seconds to date object

Convert a timestamp ts (number of seconds in epoch-time) to a date with time d. E.g. 0 -> 1970-01-01 00:00:00

import java.util.Date;
Date d = new Date(ts * 1000);

Since the date constructor expects a parameter that represents number of milliseconds since epoch, we must multiply ts by 1000 to convert it to milliseconds.
import static java.lang.System.currentTimeMillis;
long ts = currentTimeMillis();
String d = "%tc".formatted(ts);
import java.time.LocalDateTime;
import java.time.ZoneOffset;
LocalDateTime d = LocalDateTime.ofEpochSecond(ts, 0, ZoneOffset.UTC);
import java.time.Instant;
Instant d = Instant.ofEpochSecond(ts);
import java.text.SimpleDateFormat;
import java.util.Date;
Date d = new Date(ts * 1000);
SimpleDateFormat f = new SimpleDateFormat();
f.applyPattern("yyyy-MM-dd HH:mm:ss");
String s = f.format(d);
#include <chrono>
#include <ctime>
std::time_t d = std::chrono::system_clock::to_time_t(ts);

ts is a time_point (epoch)

New implementation...
< >
elbrujohalcon