DEV Community

Haruka Kakiuchi
Haruka Kakiuchi

Posted on

Display the current time

Goal: 01 / 01 / 2000, 12:00

const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth() + 1}`.padStart(2, '0');
const year = now.getFullYear();
const hour = now.getHours();
const min = now.getMinutes();
Enter fullscreen mode Exit fullscreen mode
  • padStart() needs to be used with a string.
  • padStart() fills the first argument's number of minutes with the elements of the second argument.
hoge.textContent = `${day}/${month}/${year}, ${hour}:${min}`;
Enter fullscreen mode Exit fullscreen mode

If I want to show 'TODAY' or 'Yesterday' when the day is matched.

const calcDayPassed = (date1, date2) => Math.round(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24)); // get time stamp

  const daysPassed = calcDayPassed(new Date(), date) 

  if(daysPassed === 0) return 'Today';
  if(daysPassed === 1) return 'Yesterday';
  if(daysPassed <= 7) return `${daysPassed} days ago`;
  else {
    const day = `${date.getDate()}`.padStart(2, '0');
    const month = `${date.getMonth() + 1}`.padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  }
Enter fullscreen mode Exit fullscreen mode

Globalisation

const now = new Date();
const options = {
 hour: 'numeric',
 minute: 'numeric',
 day: 'numeric',
 month: 'numeric',
 year: `numeric`,
}

const locale = navigator.language;

hoge.textContent = new Intl.DateTimeFormat(currentAccount.locale, options).format(now);

Enter fullscreen mode Exit fullscreen mode

MDN : Int

Top comments (0)