使用javascript的多个日期



所以这很有效,但我知道这不是真正正确的方法。有人能给我一些写得更好的建议吗?我该如何更有效地写这篇文章?

// two weeks prior start
var date = new Date();
$('#twoWeeksPrior').text(get_last_date(date));
function str_pad(n) {
return String('00' + n).slice(-2);
}
function get_last_date(date) {
var y = date.getFullYear(),
m = date.getMonth(),
day = date.getDate();
// get date two weeks prior
var result = new Date(y, m, day - 14, 0);
return result.toLocaleDateString().split(",")[0]
}
// seven days prior start
var date2 = new Date();
$('#sevenDaysPrior').text(get_last_date_seven(date));
function str_pad(n) {
return String('00' + n).slice(-2);
}
function get_last_date_seven(date) {
var y = date.getFullYear(),
m = date.getMonth(),
day = date.getDate();
// get date one week prior
var result = new Date(y, m, day - 7, 0);
return result.toLocaleDateString().split(",")[0]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id='twoWeeksPrior'></span>
<span id='sevenDaysPrior'></span>

您可以修改getTime:

let date = new Date();
// MILLISECONDS * SECONDS * MINUTES * HOURS
// One day prior is the amount of milliseconds in 1 day
let onedayprior = 1000 * 60 * 60 * 24;
let oneweekprior = onedayprior * 7;
let twoweeksprior = onedayprior * 7 * 2;
$('#twoWeeksPrior').text(new Date(date.getTime() - twoweeksprior).toLocaleDateString());
$('#sevenDaysPrior').text(new Date(date.getTime() - oneweekprior).toLocaleDateString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id='twoWeeksPrior'></span>
<span id='sevenDaysPrior'></span>

相关内容

  • 没有找到相关文章

最新更新