0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】現在の日付時刻をyy-mm-dd-hh-mm の形で返す関数

Posted at

備忘録

現在の日付時刻をyymmddhhmm の形で返す関数

formatDate.js
 function formatDate(dt) {
    const y = ('00'+dt.getFullYear()).slice(-2);
    const m = ('00' + (dt.getMonth()+1)).slice(-2);
    const d = ('00' + dt.getDate()).slice(-2);
    const h = ('00' + dt.getHours()).slice(-2);
    const mm = ('00' + dt.getMinutes()).slice(-2);
    return (y + m + d +  h  + mm);
  }
result.js
> formatDate(new Date());
'2205261737'

slice(-2) は、文字列の右から数えて2文字目までを抜き出すので、getFullYear()2022と取得し22を出力している

ハイフンをつける場合(yy-mm-dd-hh-mm)

formatDate.js
 function formatDate(dt) {
    const y = ('00'+dt.getFullYear()).slice(-2);
    const m = ('00' + (dt.getMonth()+1)).slice(-2);
    const d = ('00' + dt.getDate()).slice(-2);
    const h = ('00' + dt.getHours()).slice(-2);
    const mm = ('00' + dt.getMinutes()).slice(-2);
    return (y + '-' + m + '-' + d + '-' + h  + '-' + mm);
  }
result.js
> formatDate(new Date());
'22-05-26-17-37'
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?