用JavaScript计算日期 [英] Calculating Date in JavaScript
问题描述
所有
Thansk提前
我不得不做类似的事情(不是在JS,但算法类似)
现在,在我开始之前,澄清我假设这是不管这个月份的长短,每两周发生一次,而在第二和第四个星期二都不会,不管最后一次发生什么,这样比较简单,解决
选择过去发生此事件的日期(或第一次发生的日期),我们将在以下代码中将此日期称为 base
p>
var base = new Date('first of first occurrence');
var one_day = 1000 * 60 * 60 * 24; //以毫秒为单位的日期长度
//假设我们关心如果倒计时应该从今天开始
//如果您正在构建日历等等,这可能会有所不同
var date_to_check = new Date();
var diff_in_days = math.floor(date_to_check-base)/ one_day);
var days_since_last_reset = diff_in_days%14;
if(days_since_last_reset == 0){
// date_to_check是以
//i.e为基础的每两周周期中的同一天。今天在某个时候是你想要显示定时器
//如果你只想在某些时间之间显示定时器,
//在这里添加另一个检查
} else {
//下一次重新设置(14 - days_since_last_reset)days from date_to_check
}
或代码高尔夫球版本:
if(Math.floor((new Date() - new Date第一次出现'))/ 1000/60/60/24)%14 == 0)
//重置/启动计时器
I am currently looking to calculate a custom date in JavaScript and my head is beginning to hurt thinking about it. I have a countdown clock that is to start every other Tuesday at 12pm. I have the countdown function working properly using the jQuery countdown plugin by Keith Wood but need assistance in calculating every other Tuesday of the month and having it reset on this day.
All help is greatly appreciated as always.
Thansk in advance
I've had to do something similar (not in JS but the algorithm is similar enough)
Now, before i start, to clarify i'm assuming this is something that happens fortnightly regardless of the length of the month, and not on the second and 4th Tuesday regardless of when it last happened, which is simpler to solve
Pick a date in the past that this event has occured on (or the date of the first occurrence) , we'll call this date base
in the following code
var base=new Date('date of first occurrence');
var one_day=1000*60*60*24; //length of day in ms
// assume we care about if the countdown should start today
// this may be different if you are building a calendar etc.
var date_to_check=new Date();
var diff_in_days=math.floor(date_to_check-base)/one_day);
var days_since_last_reset= diff_in_days%14;
if(days_since_last_reset == 0){
//date_to_check is the same day in the fortnightly cycle as base
//i.e. today at some point is when you'll want to show the timer
//If you only want to show the timer between certain times,
//add another check here
}else{
//next reset in (14 - days_since_last_reset) days from date_to_check
}
Or the code-golf-esque version:
if( Math.floor((new Date()-new Date('date of first occurrence'))/1000/60/60/24)%14 == 0 )
//reset/start timer
这篇关于用JavaScript计算日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!