Ajax get Date in dd/mm/yyyy format

22,912

Solution 1

Like so:

("0"+1).slice(-2);  // returns 01
("0"+10).slice(-2); // returns 10

Complete example:

var d = new Date(2011,1,1); // 1-Feb-2011
var today_date =
    ("0" + d.getDate()).slice(-2) + "/" +
    ("0" + (d.getMonth() + 1)).slice(-2) + "/" + 
    d.getFullYear();
// 01/02/2011

Solution 2

Well, you could simply check the length of d.getDate()and if it's 1 then you add a zero at the beginning. But you would like to take a look at format() to format your dates?

Solution 3

Try this (http://blog.stevenlevithan.com/archives/date-time-format):

var d = new Date();
d.format("dd/mm/yyyy"); 

Solution 4

Try this, this is more understandable.:

  var currentTime = new Date();
  var day = currentTime.getDate();
  var month = currentTime.getMonth() + 1;
  var year = currentTime.getFullYear();

  if (day < 10){
  day = "0" + day;
  }

  if (month < 10){
  month = "0" + month;
  }

  var today_date = day + "/" + month + "/" + year;
  document.write(today_date.toString());

And result is :

07/05/2011

Share:
22,912
Beginner
Author by

Beginner

I am a Beginner to everything

Updated on August 05, 2020

Comments

  • Beginner
    Beginner almost 4 years
    var d = new Date();
        var today_date = d.getDate() + '/' + month_name[d.getMonth()] + '/' + d.getFullYear();
    

    This is how I am getting a date. It works with a slight problem. For todays date 7th of June 2011 it returns 7/11/2011, what i want it to return is 07/11/2011?

    Anyone know how?