Skip to content

Instantly share code, notes, and snippets.

@jkrems
Last active August 10, 2016 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jkrems/aef904cc60fb7bcfb89ba65c7fb8f134 to your computer and use it in GitHub Desktop.
Save jkrems/aef904cc60fb7bcfb89ba65c7fb8f134 to your computer and use it in GitHub Desktop.

Getting seconds or milliseconds since January 1, 1970, 00:00:00 GMT in various languages

Second-Native

C (1972)

// ms
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
spec.tv_sec * 1e3 + round(spec.tv_nsec / 1.0e6)

// s
time(NULL)

C++ (1983)

The millisecond parts are part of C++11.

// ms
using namespace std::chrono;
duration_cast<milliseconds>(system_clock::now().time_since_epoch())

// s, technically cheating because it's using the C-way of doing it
time(NULL)

PHP (1998)

The "as float" microtime arg was added in PHP5 (2004).

# ms
round(microtime(true) * 1000);

# s
time();

Python (1991)

# ms
# python -c 'import time; print(round(time.time() * 1000))'
import time
round(time.time() * 1000)

# s
# python -c 'import time; print(round(time.time()))'
import time
round(time.time())

Ruby (1995)

# ms
# ruby -e 'require "date"' -e 'puts((Time.now.to_f * 1000).to_i)'
(Time.now.to_f * 1000).to_i

# s
# ruby -e 'require "date"' -e 'puts((Time.now.to_f * 1000).to_i)'
Time.now.to_i

Rust

// ms
use std::time::{Duration, SystemTime, UNIX_EPOCH};
match SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() / 1000 + d.subsec_nanos() * 1e6) {
  Ok(n) => println!("{}", n),
  Err(..) => {}
}

// s
use std::time::{Duration, SystemTime, UNIX_EPOCH};
match SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()) {
  Ok(n) => println!("{}", n),
  Err(..) => {}
}

Millisecond-Native

Java (1995)

// ms
System.currentTimeMillis()
// or:
new Date().getTime()

// s
Math.round(System.currentTimeMillis() / 1000)

JavaScript (1995)

// ms
// node -p 'Date.now()'
Date.now()
// or:
new Date().getTime()

// s
// node -p 'Date.now()/1000|0'
Math.round(Date.now()/1000)

No Preference

C# (2000)

// ms
DateTimeOffset.Now.ToUnixTimeMilliseconds()

// s
DateTimeOffset.Now.ToUnixTimeSeconds()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment