-2

I would like to have javascript return the current time in a format that looks like "2011-11-03 11:18:04".

I tried var XX = date() but the returned format is not what I want. It looks like

Tue Mar 15 2013 06:45:40 GMT-0500

How can I format time to look like "2011-11-03 11:18:04"?

Thank you very much.

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
guagay_wk
  • 26,337
  • 54
  • 186
  • 295

3 Answers3

5

After creating the date correctly (var xx = new Date();, note the capital and the new), you have two choices:

  1. Use the various methods of Date instances (MDN | specification) and build the string yourself.

  2. Use a library like MomentJS to do the work for you.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Using Date functions-

//MM-dd-yyyy HH:mm:ss format
function formatDateTime(d){
  function addZeros(n){
     return n < 10 ? '0' + n : '' + n;
  }
  return addZeros(d.getFullYear()+1)+"-"+ addZeros(d.getMonth()) + "-" + d.getDate() + " " + 
           addZeros(d.getHours()) + ":" + addZeros(d.getMinutes()) + ":" + addZeros(d.getMinutes());
}

With momentjs-

var now = moment().format("YYYY-MM-DD HH:mm:ss");

jsFiddle

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
1

Here is a complete working solution

<script type="text/javascript">
function giveNewDate(){
var d = new Date();
var r = d.getFullYear()+"-"+zPlus(d.getMonth())+"-"+zPlus(d.getDate())+" "+zPlus(d.getHours())+":"+zPlus(d.getMinutes())+":"+zPlus(d.getSeconds());

function zPlus(digit){
    var digit = parseInt(digit);
    if (digit < 10){
    return "0"+digit;
    }else{
        return ""+digit;
    }
}
return r;
}

//to use: just call the giveNewDate() function
alert(giveNewDate());
</script>

In your script, simply call the giveNewDate() function where you need the text to appear.

Have a great day!

:)

Jack Amoratis
  • 653
  • 2
  • 7
  • 22