0

I want to display a date stamp on my view. The format I want is "20120712" for 07/12/2012.

Here is what I have so far,

$(function () {
    $(document).ready(function () {
        var now = new Date();
        var nowYear = now.getFullYear();
        var nowMonth = now.getMonth() + 1;
        var nowDate = now.getDate();

        var DateStamp = nowYear.toString() + nowMonth.toString() + nowDate.toString();

        $("#DateStamp").val(DateStamp);
    });

I am able to display: "2012712" but I want to display leading zeros for month and date for single digit months and dates, e.g. "20120712"

user793468
  • 4,898
  • 23
  • 81
  • 126

2 Answers2

1

Try this: Working demo http://jsbin.com/awates/6 (watch the alert going)

.slice(-2) and you can add "0" to the day or month, and just ask for the last two since those are always the two we want. var nowMonth = ('0'+ (now.getMonth() + 1));

Read this a good read: Javascript add leading zeroes to date

Hope it fits the cause, :)

Explanation:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, you can add "0" to the day or month, and just ask for the last two since those are always the two we want. var nowMonth = ('0'+ (now.getMonth() + 1));

So if the MyDate.getMonth() returns 7, it will be:

("0" + "7").slice(-2) // Giving us "07"

code

$(function () {
    $(document).ready(function () {
        var now = new Date();
        var nowYear = now.getFullYear();
        var nowMonth = ('0'+ (now.getMonth() + 1));
        var nowDate = now.getDate();
        alert(nowMonth);
        var DateStamp = nowYear.toString() + nowMonth.toString().slice(-2) + nowDate.toString();
    alert(DateStamp);
       // $("#DateStamp").val(DateStamp);
    });
});
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

I havent tested this code but you might be able to do following:

function addZero(val){
var result;
if(val < 10){
    result = '0'+val;
} 
return result;
}



var nowDate = addZero(now.getDate());
Subash
  • 7,098
  • 7
  • 44
  • 70