'JavaScript Date calculation and conversion issue

I am trying to do some date calculations in javascript but having trouble:

var days = 5;
var init_date = '22-DEC-21';
var result;

today = new Date();
result = today - days;

result I expect to have a date value but it is a numeric value. How can I convert it to date?

Also the variable init_date will need to be converted to date and compared with result. How can this be done in JavaScript?



Solution 1:[1]

To get date minus, say 5 days you can use methods of JS Date() API like this:

let date = new Date();
date.setDate((date.getDate() - 5));

Note: it will return the date in milliseconds, like this:

//1642972791097

To convert it to standard date, use this:

new Date(1642972791097);
//Sun Jan 23 2022 23:19:51 GMT+0200 (Israel Standard Time)

To convert it to local date format, use this:

new Date(1642972791097).toLocaleDateString()
//'1/23/2022' 

To properly parse the string representation like '22-DEC-21' you will need to keep helper object monthsNames. See code example:

let monthsNames = {
    'JAN': 0,
    'FEB': 1,
    'MAR': 2,
    'APR': 3,
    'MAY': 4,
    'JUN': 5,
    'JUN': 6,
    'AUG': 7,
    'SEP': 8,
    'OCT': 9,
    'NOV': 10,
    'DEC': 11
}

let initDate = new Date();
let initDateString = '22-DEC-21';
let initDateArray = initDateString.split('-');
initDate.setDate(initDateArray[0]);
initDate.setMonth(monthsNames[initDateArray[1]]);
initDate.setFullYear(Number('20' + initDateArray[2]));

console.log(initDate);
//Wed Dec 22 2021 23:15:47 GMT+0200 (Israel Standard Time)

Regarding comparing the dates: the easiest way to converts the dates to milliseconds. Say, you have 2 variables keeping the dates in standard format: date1 and date2. So:

let date1Milli = date1.getTime(); // date in milliseconds
let date2Milli = date2.getTime();
console.log(date1Milli > date2Milli);
// true or false 

Solution 2:[2]

You can use this to begin with:

const daysToSeconds = x => x * 24 * 60 * 60;
const dateToSeconds = x => new Date(x).valueOf() / 1000;
const secondsToDate = x => new Date(x * 1000).toLocaleString().split(",").join("");

const today  = dateToSeconds(new Date());
const days   = daysToSeconds(5);
const result = secondsToDate(today - days);

Other than that, it is not really clear what you want to do with var init_date = '22-DEC-21'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 bbbbbbbbb