Skip to content

Instantly share code, notes, and snippets.

@MattMS
Last active July 26, 2018 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattMS/6ba9ca7226adeacf58a55297a657d154 to your computer and use it in GitHub Desktop.
Save MattMS/6ba9ca7226adeacf58a55297a657d154 to your computer and use it in GitHub Desktop.
Convert the current UTC time to different formats.

Time format examples

Gets the current UTC time to seconds accuracy (max available with date). Using date and sed so these can run in Alpine Linux.

As file path

For example: 1999/12/31/23/59/59

Ash

date -Iseconds -u | sed -En '1{s/[-+:T]/\//g; s/^(.{0,19}).*$/\1/g; p}'

JS

(new Date()).toISOString().replace(/[-:T]/g, '/').slice(0, 19)

Ramda

const ensure_int = R.unless(R.is(Number), parseInt)
const timestamp_to_iso8601_text = R.pipe(ensure_int, R.constructN(1, Date), R.invoker(0, 'toISOString'))
const as_path = R.pipe(timestamp_to_iso8601_text, R.replace(/[-:T]/g, '/'), R.slice(0, 19))
as_path(Date.now())

To include milliseconds:

const as_path = R.pipe(timestamp_to_iso8601_text, R.replace(/[-.:T]/g, '/'), R.init)

Note the Ramda example is longer because it creates other functions that may be useful.

To convert path back to timestamp:

const collapse_path = R.pipe(R.split('/'), R.map(parseInt), R.apply(R.constructN(7, Date)), R.invoker(0, 'valueOf'))

In Docker tag friendly format

For example: 19991231t235959

Ash

With cut and tr:

date -Is -u | cut -c -19 | tr -d '-' | tr -d ':' | tr 'T' 't'

With sed:

date -Iseconds -u | sed -En '1{s/[-+:]//g; s/^(.{0,15}).*$/\L\1/g; p}'

Links

https://www.gnu.org/software/sed/manual/sed.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment