tags:

views:

89

answers:

6

I'm not familiar with time operations in javascript.

I tried new Date(); which gives the result in wrong format:

Thu Dec 24 2009 14:24:06 GMT+0800

How to get the time in format of 2009-12-24 14:20:57

+1  A: 
<script type="text/javascript">
  function formatDate(d){
   function pad(n){return n<10 ? '0'+n : n}
   return [d.getUTCFullYear(),'-',
          pad(d.getUTCMonth()+1),'-',
          pad(d.getUTCDate()),' ',
          pad(d.getUTCHours()),':',
          pad(d.getUTCMinutes()),':',
          pad(d.getUTCSeconds())].join("");
  }

  var d = new Date();
  var formattedDate = formatDate(d); 
</script
Chandra Patni
+1  A: 

to format date

<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
//-->
</script>

prints : 24-12-2009

to format time you can do

<script type="text/javascript">
<!--

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

var curr_sec = d.getSeconds();

document.write(curr_hour + ":" + curr_min + ":" 
+ curr_sec);

//-->
</script>

prints : 8:32:33

NetCaster
A: 

Here is a nice on

JavaScript (ActionScript) Date.format

or you can use like this

var dt = new Date();

var timeString = dt.getFullYear() +  "-" + dt.getMonth() + "-" + dt.getDate() + " " + dt.getHours() + ":" + dt.getMinutes() +":" + dt.getSeconds()
rahul
A: 

Use the pieces of the date as found here, to format to your liking.

ie.

var now = new Date();
var formatStr = now.getFullYear() + " - " + now.getMonth() + " - " + now.getDate();
// formatStr = "2009 - 12 - 23"
Myles
+2  A: 

There is no cross browser Date.format() method currently. Some toolkits like Ext have one but not all (I'm pretty sure jQuery does not). If you need flexibility, you can find several such methods available on the web. If you expect to always use the same format then:

var now = new Date();
var pretty = [
  now.getFullYear(),
  '-',
  now.getMonth() + 1,
  '-',
  now.getDate(),
  ' ',
  now.getHours(),
  ':',
  now.getMinutes(),
  ':',
  now.getSeconds()
].join('');
Rob Van Dam
Think carefully about whether you want this in local time or with a time zone (or "Z"), also padding is needed. ES5 provides a toISOString() method, available in some browsers today.
peller
A: 

My JavaScript implementation of Java's SimpleDateFormat's format method may help you: http://www.timdown.co.uk/code/simpledateformat.php

Tim Down