Unix time in various languages - A reference
What is Unix time?
Unix time (also known as POSIX time or erroneously as Epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.
UTaaS (Unix Timestamp as a Service) (generic)
curl https://icanhazepoch.com/
C
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv) {
unsigned int unix_time = (unsigned) time(NULL);
fprintf(stdout, "%u\n", unix_time);
return 0;
}
C++
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char **argv) {
unsigned int unix_time = (unsigned) time(NULL);
cout << unix_time << endl;
return 0;
}
Elixir
# first way
DateTime.utc_now |> DateTime.to_unix
# second way
System.system_time(:second)
Erlang
os:system_time(second).
Golang
now := time.Now()
unixTs := now.Unix()
Java
long timestamp = System.currentTimeMillis()/1000;
System.out.println(timestamp);
Java 8 brings a new API to work with date and times, Instant. A good read about why JSR-310 is not same as joda-time. You can get current unix time on Java 8 by doing something like below:
long timestamp = Instant.now().getEpochSecond();
System.out.println(timestamp);
Javascript
Math.floor(new Date() / 1000)
Moment is very popular in javascript world for playing with dates in javascript. Below is the momentjs example.
var moment = require('moment');
var unixtime = moment().unix();
PHP
echo time();
//php5.3 and above
//OOP style
$date = new DateTime();
echo $date->getTimestamp();
//procedural style
$date = date_create();
echo date_timestamp_get($date);
Python
from time import time
print(int(time()))
import datetime
print(int(datetime.datetime.utcnow().timestamp()))
Ruby
Time.now.to_i