-1

I am new to js and I am trying to fiddle with the javascript dates. I have a following date in the format 01-JAN-2016 and I need to subtract 1 day from it. I tried

var dateVar = '01-JAN-2016'
var d = new Date(dateVar);
alert(d);
alert(d-1);

It gives me a date and time in long no. But I want it want it to be '31-DEC-2016' How can I add the format dd-MMM-yyy to it?

tintin
  • 4,971
  • 14
  • 57
  • 81
  • Please! refer to this link - http://stackoverflow.com/questions/16401804/how-to-get-the-day-before-a-date-in-javascript and delete this answer. – Utkarsh Dubey Apr 10 '17 at 12:01
  • Use some library or do a bit of tweak coding use .getDate() .getMonth() .getFullYear() – Vinod Louis Apr 10 '17 at 12:02
  • have a look at the following: http://stackoverflow.com/questions/25136760/from-date-i-just-want-to-subtract-1-day-in-javascript-angularjs Hope it can help! – AkrisManta Apr 10 '17 at 12:02
  • For converting date to format *dd-mmm-yyyy* please refer http://stackoverflow.com/questions/27480262/get-current-date-in-dd-mon-yyy-format-in-javascript-jquery – Aniket Bhansali Apr 10 '17 at 12:08

1 Answers1

3

You can use datejs library

var dateVar = new Date('01-JAN-2016')
var d = dateVar.add(-1).day().toString('dd-MMM-yyyy');
alert(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>

or with plain javascript, you can do like this!

var monthNames = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
  "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
];

var date = new Date('01-JAN-2016')
date.setDate(date.getDate() - 1)
date = date.getDate()+"-"+monthNames[date.getMonth()]+"-"+date.getFullYear()

console.log(date)
Gaurav Chaudhary
  • 1,391
  • 10
  • 25