[removed] output current datetime in YYYY/mm/dd hh:m:sec format

后端 未结 6 681
囚心锁ツ
囚心锁ツ 2020-11-30 08:21

I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec

How do I achieve that with Javascript?

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:57

    No library, one line, properly padded

    const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
    

    It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

    Local time instead of UTC

    const now = new Date();
    const offsetMs = now.getTimezoneOffset() * 60 * 1000;
    const dateLocal = new Date(now.getTime() - offsetMs);
    const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
    

提交回复
热议问题