0

Like i need to get todays date in format like 20120924 (yyyymmdd).How can i get this in javascript.

vetri02
  • 3,199
  • 8
  • 32
  • 43
  • 1
    Duplicate so far [How do I format a Javascript Date?](http://stackoverflow.com/questions/986657/how-do-i-format-a-javascript-date?rq=1) – Andreas Rohde Sep 24 '12 at 12:51
  • refer http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript it will help you... – V.J. Sep 24 '12 at 12:56

5 Answers5

3

You could add a method to the date prototype, so you can use it on any date object:

Date.prototype.toMyString = function () {

    function padZero(obj) {
          obj = obj + '';
          if (obj.length == 1)
              obj = "0" + obj
          return obj;
    }

    var output = "";
    output += this.getFullYear();
    output += padZero(this.getMonth()+1);
    output += padZero(this.getDate());

    return output; 
}

var d = new Date();
alert(d.toMyString());  // Today

var otherDate = new Date(2012,0,1);
alert(otherDate.toMyString());​  //Jan 1 2012

Fiddle: http://jsfiddle.net/johnkoer/4rk7K/10/

John Koerner
  • 37,428
  • 8
  • 84
  • 134
3

This worked for me.

var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Tang
  • 43
  • 1
  • 7
2

Try this.

​var date = new Date();
var year = date.getFullYear().toString();
var month = date.getMonth().toString();
var day = date.getDate().toString();

if (parseInt(month) < 10) month = "0" + month;
if (parseInt(day) < 10) day = "0" + day;

var parsedDate = year + month + day;

(edit) Improved this function by making the day equate to the day of the month, rather than the day of the week.

Motionharvest
  • 407
  • 4
  • 10
Paul Aldred-Bann
  • 5,840
  • 4
  • 36
  • 55
0

How about

date = new Date().toJSON().substr(0,10).split("-")
date = date[0] + date[1] + date[2]

Edit:
This will return the UTC date, not local date...

For local date, you could use:

date = new Date().toLocaleDateString().split("/");  // "M/D/YYYY"
date[0] = date[0].length == 1 ? "0" + date[0] : date[0];
date[1] = date[1].length == 1 ? "0" + date[1] : date[1];
date = date[2] + date[0] + date[1];
Guy de Carufel
  • 466
  • 4
  • 8
-2
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_year + curr_month + curr_date);

That should give the right date:)

Keethanjan
  • 365
  • 1
  • 7