Search code examples
javascriptepochdate-conversion

Stop date to epoch conversion in javascript


I have a code where I try to set date 20 days back from current date on server. I have used a variable(say dateRange) in javascript to get current date. But on using the same variable second time for setDate() function value of dateRange is changed to epoch from date. I know I can convert epoch to date and proceed but is there a way to stop this automatic conversion.

var dateRange=new Date(currentDate);  
dateRange = dateRange.setDate(dateRange.getDate() - 20);

Solution

  • Internally dates are stored as milliseconds from the epoch date. To achieve what you are trying to do you can subtract the number of milliseconds that corresponds to 20 days:

    var currentDate = "2019-07-29T07:14:57.269Z";
    var dateRange = new Date(currentDate);  
    
    var pastDate = new Date(dateRange - 1000 * 60 * 60 * 24 * 20);
    
    console.log('current', currentDate);
    console.log('20 days ago', pastDate);

    anyway if you are doing a lot of date/time manipulations in your app i suggest you to use this library: https://momentjs.com/