1

I need my date to be in ccyymmdd format to add a day and pass over to a cobol application via xml. I also need to convert the new date with the added day to mm/dd/ccyy format to place into my slickgrid. My boss believes there has to be an easier way however, I can't seem to find one without using jquery or adding another library. Here is the code I am using;

        // Roll date for status R1(rolled) today plus 1 day.
        var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
        (rDate++);
        // Convert rDate back to useable date for updating ActionDate when rolling clt.
        var uDate = (String(rDate)).replace(/(\d{4})(\d{2})(\d+)/, "$2/$3/$1"); 
Tang
  • 43
  • 7

3 Answers3

1

The Date object in JavaScript has getFullYear, getMonth, and day methods, which means you can do:

If you had a function pad(num, digits) which pads a number with leading zeroes, you can have:

var str = pad(date.getFullYear(), 4) + pad(1+ date.getMonth(), 2) + pad(date.getDate(), 2)

From Pad a number with leading zeros in JavaScript on stackoverflow, you can get a pad functio:

function pad(n, width) {
  n += '';
  return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
Community
  • 1
  • 1
EyasSH
  • 3,400
  • 17
  • 33
0

I don't think it's better, but another approach:

var d = new Date();
var datestr = [ d.getFullYear(), ('0' + (1+d.getMonth())).substr(-2), ("0" + d.getDate()).substr(-2) ].join('');

Two thing to clarify: getMonth() returns 0-based month number, hence the need to add 1. And the ("0" + number).substr(-2) is used to add leading zeroes to single digit numbers, because substr(-2) returns two last characters of a string.

pawel
  • 30,843
  • 6
  • 50
  • 50
0

So to preserve what you are doing (adding a day to the date), one solution is:

var rDate = new Date();
rDate.setDate(rDate.getDate() + 1);
var printDate = rDate.getFullYear()+('0'+(rDate.getMonth()+1)).slice(-2)+('0'+(rDate.getDate())).slice(-2);

The advantage here is that rDate is always a real Date object, so you don't have to convert it back - you can just use it for any output format you wish.

Raad
  • 4,010
  • 1
  • 21
  • 41