この質問にはすでに答えがあります:
- または 日付にXヶ月を追加するJavaScript関数 または 17の答え または または
今から1ヶ月前の時刻のUNIXタイムスタンプを取得するにはどうすればよいですか?
私はDate()
を使う必要があることを知っています
この質問にはすでに答えがあります:
今から1ヶ月前の時刻のUNIXタイムスタンプを取得するにはどうすればよいですか?
私はDate()
を使う必要があることを知っています
単純な答えは次のとおりです。
// Get a date object for the current time
var d = new Date();
// Set it to one month ago
d.setMonth(d.getMonth() - 1);
// Zero the hours
d.setHours(0, 0, 0);
// Zero the milliseconds
d.setMilliseconds(0);
// Get the time value in milliseconds and convert to seconds
console.log(d/1000|0);
7月31日から1ヶ月を減算すると、6月31日になります。これは1ジュリに変換されます。同様に、3月31日は2月31日になります。これは、うるう年になっているかどうかによって2または3月3日に変換されます。
月をチェックする必要があります:
var d = new Date();
var m = d.getMonth();
d.setMonth(d.getMonth() - 1);
// If still in same month, set date to last day of
// previous month
if (d.getMonth() == m) d.setDate(0);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
// Get the time value in milliseconds and convert to seconds
console.log(d / 1000 | 0);
JavaScriptの時刻値は1970-01-01T00:00:00Zからのミリ秒単位であり、UNIXの時刻値は同じエポックからの秒単位であるため、1000で除算されることに注意してください。