H
H
HappyMen2019-07-02 17:02:23
JavaScript
HappyMen, 2019-07-02 17:02:23

How to get and format the current time?

I need to get current date and time in Y-m-d H:M:S.
If possible without third party libraries.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-07-02
@HappyMen

const formatDate = (date = new Date()) => {
  const
    Y = date.getFullYear(),
    m = `0${date.getMonth() + 1}`.slice(-2),
    d = `0${date.getDate()}`.slice(-2),
    H = `0${date.getHours()}`.slice(-2),
    M = `0${date.getMinutes()}`.slice(-2),
    S = `0${date.getSeconds()}`.slice(-2);

  return `${Y}-${m}-${d} ${H}:${M}:${S}`;
};

or
const formatDate = (date = new Date()) => {
  const dateWithTimezone = new Date(date);
  dateWithTimezone.setHours(date.getHours() - date.getTimezoneOffset() / 60);
  return dateWithTimezone.toISOString().replace('T', ' ').replace(/\..+/, '');
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question