Javascript get Date()

1–2 minutes

read

To get a new date we can use

var date = new Date();

This will return a date in a format : Sun Jul 25 2021 14:12:05 GMT+0530 (India Standard Time)

Most of times we don’t have to show the date in this format. We can control that using a trick. Before that we should know some of the functions that we can use on this Date.

  • date.getDay()
  • date.getMonth()
  • date.getFullYear()

This is self explanatory by the name that they will return the day, month and year respectively.

date.getDay() will return the day. Example: 2,3,23 etc. but without the 0 appended in starting for single digit numbers.

Combining all the facts in a single function which accepts the value which is the date that we want. For example if you pass value as 1 then it will returns yesterdays date, if it is 2 then it will return day before yesterday.

function getDate(value) {
  let date = new Date();
  date.setDate(date.getDate() - value);
  let day = date.getDate();
  let month = date.getMonth() + 1;
  return (day < 10 ? '0' : '') + day + '/' + (month < 10 ? '0' : '') + month  + '/' + date.getFullYear();
}

Leave a comment