📌
現在の日付を取得する
現在の日付を取得して、それを任意のスタイルにしたString型にして返す関数
// * 現在の日付を取得
const CurrentDate = () => {
const today = new Date()
const year = today.getFullYear()
const month = ('0' + (today.getMonth() + 1)).slice(-2)
const day = ('0' + today.getDate()).slice(-2)
return year + '-' + month + '-' + day + ' '
}
// * 返り値 : 2022-12-20 (String型)
最後のreturn文で'-'を'.'にするとか'月'にするとかすれば、その形で日付を取得できる
※曜日の取得は不明
// * ファイルアップロード日の取得
const CurrentDate = () => {
const today = new Date()
const year = today.getFullYear()
const month = ('0' + (today.getMonth() + 1)).slice(-2)
const day = ('0' + today.getDay()).slice(-2)
const hours = ('0' + today.getHours()).slice(-2)
const minutes = ('0' + today.getMinutes()).slice(-2)
const seconds = ('0' + today.getSeconds()).slice(-2)
return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
Discussion
逆に、文字列を渡してもDate型に変換してくれる
locale は、時間の場所を指定している(locale:jaなら日本時間)
new Date() の引数は、空なら問題ないが、" " や undifined だとエラーが出る
1か月前の日付を取得する
(月末の足りない日付の対応は、JSデフォルトの対応のみ)
3月30日の1か月前 → 3月2日
4月1日の1か月前 → 3月1日
getDayをすると、平日の日数(5)が取得されてしまう