Logo

Programming-Idioms

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

Idiom #99 Format date YYYY-MM-DD

Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.

let x = d.toISOString().slice(0, 10)

toISOString returns a date like "2011-10-05T14:48:00.000Z".

10 is the length of "YYYY-MM-DD".

The builtin Date type has some serious problems. You may want to use a custom date type.
let y = d.getFullYear(),
    m = d.getMonth() + 1,
    D = d.getDate(), x
m = m.toString().padStart(2, '0')
D = D.toString().padStart(2, '0')
x = `${y}-${m}-${D}`

The `getMonth` method is zero-based—e.g., January is 0, February is 1, etc.
with Ada.Calendar.Formatting;
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (1 .. 10);

The Image function returns time as well therefore the slice.

New implementation...