-4

i would like format the Date the way i need it to be: I would like to have it that way: YYYY-MM-DD HH:MM:SS

I found that solution on the internet:

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;
}

Is there a better or "smaller" way to do it?

Bindl
  • 81
  • 2
  • 6
  • https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Daniel Suchan Apr 23 '18 at 15:43
  • i found that thread, but i basically shows that same thing i found already. So i just asked if theres a better or shorter way to do it. – Bindl Apr 23 '18 at 15:46
  • 2
    **better** is subjective and not a on-topic question on Stackoverflow. **smaller** as in shorter, maybe. Though, making this function a prototype function on `Date` i.e: `toYYYYMMDDHHMMSS()` would hide the code neatly away. – Nope Apr 23 '18 at 15:47

1 Answers1

1

What you are doing is the "best way", apart from maybe using a library for advanced Date manipulation.

For a shorter version you could pick-apart one of the standard formats with string operations like this:

function getTime() {
  return (new Date).toISOString().replace('T', ' ').substr(0, 19)
}

console.log(getTime());

EDIT 1 - Local Timezone

Here is a version that correctly handles the local timezone:

/**
 * getTime
 * Formats a date to
 * @param {(number | string)} [dateInitializer]
 * @returns {string}
 */
function getTime(dateInitializer) {
  var d = dateInitializer !== void 0 ? new Date(dateInitializer) : new Date();
  return d.toISOString().slice(0, 10) + ' ' + d.toTimeString().slice(0, 8);
}
//TEST
console.log(getTime());
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • 1
    The only word of caution here is`, as per documentation, *The timezone is always zero UTC offset* and therefore might not match the date/time OP expects and might further require the conversion to the expected timezone/local? – Nope Apr 23 '18 at 15:55