Categories
Work

Format Date into yyyy-mm-dd hh:ii:ss Format in JavaScript

This is a recurring thing I have to deal with. Here’s the code:

get_time = function() {
  var date_part, local_time, now, time_part;
  local_time = new Date();
  now = new Date(local_time.getTime() + (local_time.getTimezoneOffset() * 60000));
  date_part = "" + (this.zero_pad(now.getFullYear(), 2)) + "-" + (this.zero_pad(now.getMonth() + 1, 2)) + "-" + (this.zero_pad(now.getDate(), 2));
  time_part = "" + (this.zero_pad(now.getHours(), 2)) + ":" + (this.zero_pad(now.getMinutes(), 2)) + ":" + (this.zero_pad(now.getSeconds(), 2));
  return "" + date_part + " " + time_part;
}
zero_pad = function(number, length) {
  var str;
  str = "" + number;
  while (str.length < length) {
    str = "0" + str;
  }
  return str;
}
alert(get_time())