Error message

Deprecated function: implode(): Passing glue string after array is deprecated. Swap the parameters in drupal_get_feeds() (line 394 of /home1/tylerfra/public_html/includes/common.inc).

JavaScript Date Time YYYY MM DD HH MM SS

Category: 

Robot: "What time is it JavaScript, buddy? And when you answer, it better be in the format of 'YYYY-MM-DD HH:MM:SS' in 24 hour format with preceeding zeros on the month, day, hour, minute and second, or else!"

Me: "Relax big guy, just call this function, friend."

function js_yyyy_mm_dd_hh_mm_ss () {
  now = new Date();
  year = "" + now.getFullYear();
  month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
  day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
  hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
  minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
  second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
  return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

Here is an example usage:

alert(js_yyyy_mm_dd_hh_mm_ss());

// example alert message: 2011-05-18 15:20:12

Comments

Oops, you may not get quite what you expected! Check your return string. Hint: HH:MM:SS

tyler's picture

Thanks for pointing that out, I have adjusted the code to show : instead of -

Wow... that's a lot of Javascript code for something that should be really simple. Wish there was something like now = new Date('Y-m-d H:m:S');

tyler's picture

Yeah, it is a bummer there isn't something like PHP date string handling in JS. There probably is, somebody just needs the motivation to type it in to Google. I myself am too tired, for now.

There is a simple, javascript implementation of date format, consistent with java standard: http://llamalab.com/js/date/Date.js

Very helpful !!!

HI What if i need the time in AM and PM format.

tyler's picture

You'll have to use a mod operator of 12 on the hours, and expand the function to accommodate that accordingly.