DEV Community

loading...

Discussion on: Format Date and Time with Vanilla JavaScript

Collapse
functional_js profile image
Functional Javascript • Edited

Thanks for looking into that Bob.
I figured since you're the date/time guru, you'd have a smoother answer than the func I use, which I wrote a while back. ;)

/**
@func util
add a leading zero, if the number is a single digit number
i.e. prefix with a zero, if under 10

@param {number} t - a time or date chunk, representing either the month, day-of-month, hour, minute, or second
@return {string}
*/
const add0 = t => t < 10 ? `0${t}` : String(t);
/**
@func
get the current time, in a canonical human-readable format:
"YYYY-MM-DD ddd HH:mm"

@cons
no seconds
no milliseconds

@return {string}
*/
export const getDateStandard = () => {
  const dt = new Date();
  const y = dt.getFullYear();
  const m = add0(dt.getMonth() + 1);
  const d = add0(dt.getDate()); //day of month
  const w = dt.toDateString().substring(0, 3); //day of week enum, either Mon, Tue, Wed, Thu, Fri, Sat, Sun
  const h = add0(dt.getHours());
  const min = add0(dt.getMinutes());
  return `[${y}-${m}-${d} ${w} ${h}:${min}]`;
};
//@tests
console.log(getDateStandard());
/*
output:
[2020-09-01 Tue 09:10]
*/
Thread Thread
rfornal profile image
bob.js Author

Your solution is probably the clearest pattern. I was thinking about the toISOString and having an ability to pull out whole patterns, the problem is that is doesn't take into account the timezone offset.

Maybe something like this ...

const getDateStandard= () => {
  const d = new Date();
  let local = new Date(d);
  local.setMinutes(d.getMinutes() - d.getTimezoneOffset());

  const s_iso = local.toISOString();
  const date = s_iso.substring(0,10);
  const time = s_iso.substring(11,16);
  const dow = local.toDateString().substring(0, 3);

  return `[${date} ${dow} ${time}]`;
};

console.log(getDateStandard());
Thread Thread
functional_js profile image
Functional Javascript

That's a great one if one wants to timestamp in UTC time, or another timezone.
Thanks!

Forem Open with the Forem app