I am calculating 12 days before date from today date. But it does not return the correct date. For example, for today dat, 11/11/2013 in (mm/dd/yyyy), it returns 10/30/2013 when it should return 10/31/2013.
Here is the code
var d = new Date(); d.setDate(d.getDate() - 12); d.setMonth(d.getMonth() + 1 - 0); var curr_date = d.getDate(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); if (curr_month < 10 && curr_date < 10) { var parsedDate = "0" + curr_month + "/" + "0" + curr_date + "/" + curr_year; alert(parsedDate); } else if (curr_month < 10 && curr_date > 9) { var parsedDate = "0" + curr_month + "/" + curr_date + "/" + curr_year; alert(parsedDate); } else if (curr_month > 9 && curr_date < 10) { var parsedDate = curr_month + "/" + "0" + curr_date + "/" + curr_year; alert(parsedDate); } else { var parsedDate = curr_month + "/" + curr_date + "/" + curr_year; alert(parsedDate); }
To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.
Therefore, you can add or subtract days as easy as adding or minus the number of days in Excel. 1. Select a blank cell you will place the calculating result, type the formula =A2+10, and press the Enter key. Note: For subtracting 10 days from the date, please use this formula =A2–10.
Use the Math. abs() Function to Subtract Datetime in JavaScript.
Problem is solved
var days; // Days you want to subtract var date = new Date(); var last = new Date(date.getTime() - (days * 24 * 60 * 60 * 1000)); var day =last.getDate(); var month=last.getMonth()+1; var year=last.getFullYear();
Pure js one line solution:
new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // Tue Feb 04 2020 13:50:37 GMT...
You can use calculated value if you have no plans to change substracted value, or computed for easy change of substracted amount of days, minutes and so on.
If you plan to work more often with dates and time, I recommend to use date-fns or dayjs. date-fns seems to be better
const subDays = require('date-fns/subDays') subDays(new Date(), 7)
P.S. Why not moment.js? Moment.js is considered to be a legacy project in maintenance mode. It is not dead, but it is indeed done. See https://momentjs.com/docs/#/-project-status/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With