如何根据当前日期显示两周期间的第一天
How can I display the first day of a two week period based on the current date with?
我需要做的是获取当前日期,并根据今天的日期确定两周支付期的第一天。支付期从星期六开始。例如,今天(12/30)属于12/20的支付期。我需要做的就是将其显示为Dec 20 2014。有什么建议吗?
谢谢
使用此处的想法来计算两个日期之间的差异,您可以执行以下操作:
function calculatePeriodStart(targetDate) {
// get first day of year
var day1 = new Date(targetDate.getFullYear(), 0, 1);
// move forward to first Saturday
day1.setDate(7 - day1.getDay());
//Get 2 weeks in milliseconds
var two_weeks = 1000 * 60 * 60 * 24 * 14;
// Calculate the difference in milliseconds
var difference_ms = targetDate.getTime() - day1.getTime();
// Convert back to fortnights
var numFortnightsD = difference_ms/two_weeks;
var numFortnights = Math.ceil(numFortnightsD);
// handle if on a Saturday, so a new cycle
if(numFortnightsD == numFortnights)
{
numFortnights++;
}
// add the number of fortnights
// but take one off to get the current period
day1.setDate(day1.getDate() + (numFortnights-1)*14);
return day1;
}
// examples
console.log('-----');
// today
var today = new Date();
console.log(today + ' => ' + calculatePeriodStart(today) + ' (today)');
// just before midnight of new period
var today = new Date(2014, 11, 19, 23, 59, 59);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just before midnight of new period)');
// exactly on midnight of new period
today = new Date(2014, 11, 20);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (exactly on midnight of new period)');
// just after midnight of new period
today = new Date(2014, 11, 20, 0, 0, 1)
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just after midnight of new period)');
// just after midnight of new period next year
today = new Date(2015, 11, 19, 0, 0, 1);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just after midnight of new period next year)');
// earlier than 1st period in year
today = new Date(2014, 0, 2);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (earlier than 1st period in year)');
calculatePeriodStart()
将返回一个Date
对象。要设置显示日期的格式,您可以使用此答案。
相关文章:
- 如何在javascript中获取一年中的周数,其中周日是一周中的第一天
- 在JavaScript中重构上个月的第一天和最后一天的代码(node.js)
- jQuery UI DatePicker-禁用除每月第一天和第15天以外的所有日期
- 日历PHP-第一天出现错误
- 从javascript数组中只返回每月的第一天
- 当日期在不同月份时,如何获取本周的第一天和最后一天
- 如何使用AngularJS$locale选择一周的第一天
- Momentjs 一周的第一天
- JavaScript:获取每月的第一天和最后一天,格式为 YYYY.唰
- 如何使引导日期选择器选择当分钟视图模式:1时选择当月的最后一天而不是第一天
- 如何根据当前日期显示两周期间的第一天
- HTML5 Intl API 的一周的第一天
- 在一年的第一天获得全年回报
- 获取两个日期之间的所有日期,并仅返回该月的第一天
- 如何获得周's的第一天,使用javascript显示周号和年份
- 时刻JS,实际一周的第一天是不正确的
- jQuery ui Datepicker返回所选周的第一天
- 使用momentJs根据Locale获取一周中的第一天
- 获取一个月的第一天名称(周一、周二)
- Javascript-更改每月的第一天