Lompat ke konten Lompat ke sidebar Lompat ke footer

Get date one week ago or one month ago javascript


Hey code friends, back again at latescode.com. in the world of programming work either on the web or mobile with javascript or many other languages, sometimes we will encounter simple cases that we have to solve, many cases that we sometimes think are simple and easy. However, we still need google to get the function or code.

This time, latescode will share a simple case, namely the case for getting the date several days earlier than the current date. The code that is shared now is specifically for JavaScript, the code is as follows

function getLastWeeksDate() {

  const now = new Date();

  return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
  
  console.log(getLastWeeksDate());

}
new Date()

This function is to get the current date and time, this function is done subordinate of the javascript.

Simply to get the date that has passed we only need to get the current date minus the number of days ago that we want to get or display, but, in javascript we cannot directly use.

new Date() - 7

this will output an integer form from the date to the current second minus 7, therefore the code above we will only need to call the year to today's date by storing today's date in

const now = new.Date()

to get the year:

now.getFullYear()

to get the month:

now.getMonth()

to get the date:

now.getDate()

and to get the day and date 7 days ago we only need the current date minus 7 days with this code:

new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7)

the code above can also be used according to your needs to get the previous date or future date in javascript and not only the date, you can modify the function for the month and year too

Posting Komentar untuk "Get date one week ago or one month ago javascript"