Logo

Programming-Idioms

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

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.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);
import static java.lang.System.currentTimeMillis;
long ts = currentTimeMillis();
String d = "%tc".formatted(ts);
import java.util.Date;
Date d = new Date(ts * 1000);
import java.time.Instant;
Instant d = Instant.ofEpochSecond(ts);
import java.time.LocalDateTime;
import java.time.ZoneOffset;
LocalDateTime d = LocalDateTime.ofEpochSecond(ts, 0, ZoneOffset.UTC);
#include <chrono>
#include <ctime>
std::time_t d = std::chrono::system_clock::to_time_t(ts);
var d = DateTimeOffset.FromUnixTimeSeconds(ts).UtcDateTime;
import std.datetime, std.stdio;
auto d = SysTime(unixTimeToStdTime(ts), UTC());
var d = new DateTime.fromMillisecondsSinceEpoch(ts, isUtc: true);
Timestamp = {Seconds div 1000000, Seconds rem 1000000, 0},
calendar:now_to_universal_time(Timestamp).
import "time"
d := time.Unix(ts, 0)
import Data.Fixed (Fixed(MkFixed))
import Data.Time.Clock (secondsToNominalDiffTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
d = posixSecondsToUTCTime . secondsToNominalDiffTime . MkFixed $ toInteger ts
new Date (ts * 1000)
$d = DateTime::createFromFormat('U', $ts);
uses SysUtils;
var
  D: TDateTime;
  TS: TTimeStamp;
begin
  D := TimeStampToDateTime(TS);
end.
use DateTime qw();
my $d = DateTime->from_epoch(epoch => $ts)->strftime('%F %T');
import datetime
d = datetime.date.fromtimestamp(ts)
require 'date'
d = DateTime.strptime(ts, '%s')
extern crate chrono;
use chrono::prelude::*;
let d = NaiveDateTime::from_timestamp(ts, 0);

New implementation...
< >
elbrujohalcon