Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time in the format 2009-12-24 14:20:57 in javascript?

Tags:

javascript

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

like image 786
user198729 Avatar asked Dec 24 '09 06:12

user198729


People also ask

How do I get the current time in JavaScript?

In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.

What is the time format in JavaScript?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.


2 Answers

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('');
like image 94
Rob Van Dam Avatar answered Oct 29 '22 11:10

Rob Van Dam


<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
like image 25
Chandra Patni Avatar answered Oct 29 '22 12:10

Chandra Patni