Get a given product date
How do I get the date 3 days before the date correctly if I have a format like 07/21/2017 8:30 AM this is because I am using the Eonasdan DateTime Picker format. But when I try minus this with 3 days, I got Fri Jul 21, 2017 08:24:14 GMT + 0800 (Chinese Standard Time) as my value, but my desired output should be the same format as 07/21/2017 8:30 AM . How can I get this value even after my format?
My codes:
var d =new Date('07/21/2017 8:30 AM');
var yesterday = new Date(d.getTime() - (96*60*60));
alert(yesterday);
source to share
function formatDate(d) {
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
date = [month, day, year].join('/');
var hours = d.getHours();
var minutes = d.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date+" "+strTime;
}
var d =new Date('07/21/2017 8:30 AM');
d.setDate(d.getDate() - 3);
var yesterday = formatDate(d);
alert(yesterday);
This should work
source to share
This should do the trick:
var date = new Date('07/21/2017 8:30 AM'); // get
date.setDate(date.getDate() - 3);
console.log(date.toString());
Basically, it takes the current day from getDate()
and uses setDate()
it to update the time to 3 days in the past.
If you want to format the date, take a look at moment.js as @Robert said. You can use something like:
moment().format('MM/DD/YYYY, h:mm:ss a');
More information about the class Date
here and the documentation of the moment.
source to share
You need to use a function setDate
in the class Date
to change the date part of a date variable
var d =new Date('07/21/2017 8:30 AM');
d.setDate(d.getDate() - 3);
console.debug(d);
source to share