使用JavaScript每两周自动切换内容(已解决!)

使用JavaScript每两周自动切换内容(已解决!),javascript,schedule,Javascript,Schedule,编辑:我最终找到了解决方案,在这里发布,以防有人发现它有用。简而言之,JavaScript日期是一个很难处理的问题 原职: 我正在制作一个网页,计算这周是否是回收周,如果是的话,哪个街区会被安排回收 此演示使用先前计划的回收周的第一天作为标定日期,并从该日期开始以14天为增量计数。每14天代表一个新的回收周的开始。显示的消息会根据一天中的时间和一周中的哪一天而变化 我遇到的问题是,下一个回收周的开始日期每天有几个小时是不正确的。我认为这是一个时区的事情,但将时区设定在划界日期会产生相同的结果 最

编辑:我最终找到了解决方案,在这里发布,以防有人发现它有用。简而言之,JavaScript日期是一个很难处理的问题

原职:

我正在制作一个网页,计算这周是否是回收周,如果是的话,哪个街区会被安排回收

此演示使用先前计划的回收周的第一天作为标定日期,并从该日期开始以14天为增量计数。每14天代表一个新的回收周的开始。显示的消息会根据一天中的时间和一周中的哪一天而变化

我遇到的问题是,下一个回收周的开始日期每天有几个小时是不正确的。我认为这是一个时区的事情,但将时区设定在划界日期会产生相同的结果

最后,我改变了划界日期的日期格式,结果成功了

我从这开始

var demarcationdate = new Date("2017-03-13");
…为了这个

var demarcationdate= new Date("2017-03-13").toLocaleString("en-US", {timeZone: "America/New_York"});
…对这一点,这最终起了作用

var demarcationdate = new Date("March 13, 2017 00:00:00");
以下是CodePen上演示的链接:

HTML:

<header class="masthead" id="map">
  <div class="container h-100">
    <div class="row h-100 align-items-center">
      <div class="col-12 text-center text-white">

        <h1 class="display-4 mb-4">
          <span id="greeting" class="greeting"></span>
        </h1>

        <p class="lead">
          <span id="todaysDate"></span>
          <span id="neighborhood"></span>
          <span id="futureDate"></span>
        </p>

        <p>
          <span id="followingWeek"></span>
        </p>

      </div>
    </div>
  </div>
</header>
JS:

// greeting based on time of day
var thehours = new Date().getHours();
var greeting = document.getElementById('greeting');
var themessage;
var morning = ('Good morning!');
var afternoon = ('Good afternoon!');
var evening = ('Good evening!');

if (thehours >= 0 && thehours < 12) {
  themessage = morning; 

} else if (thehours >= 12 && thehours < 17) {
  themessage = afternoon;

} else if (thehours >= 17 && thehours < 24) {
  themessage = evening;
}

greeting.innerHTML= themessage; // show greeting, always on


// neighborhood for day of week
var scheduleCurrentDate = new Date();
var scheduleAllDays = [
  {
    day: "Sunday",
    neighborhood: "recycling pickup is scheduled for the <strong>Fairmount Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Sunday+Image"
  },
  {
    day: "Monday",
    neighborhood: "recycling pickup is scheduled for the <strong>West Market Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Monday+Image"
  },
  {
    day: "Tuesday",
    neighborhood: "recycling pickup is scheduled for the <strong>Union Street Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Tuesday+Image"
  },
  {
    day: "Wednesday",
    neighborhood: "recycling pickup is scheduled for the <strong>Broadway and State Street Neighborhoods</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Wednesday+Image"
  },
  {
    day: "Thursday",
    neighborhood: "recycling pickup is scheduled for the <strong>Downtown Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Thursday+Image"
  },
  {
    day: "Friday",
    neighborhood: "recycling pickup is scheduled for the <strong>East Hills Neighborhood</strong>",
    image:
    "https://via.placeholder.com/1920x1080/555555/666666/?text=Friday+Image"
  },
  {
    day: "Saturday",
    neighborhood: "recycling pickup is scheduled for the <strong>Kenduskeag Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Saturday+Image"
  }
];

// document.getElementById("day").innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].day;
// document.getElementById("neighborhood").innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].neighborhood + " (excluding holidays). ";
document.getElementById("map").style.background =
  "url('" + scheduleAllDays[scheduleCurrentDate.getDay()].image + "') no-repeat center"; // show background image, based on day of the week



// calculate bi-weekly schedule
function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return Math.floor((treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay);
}

// start date based on most recently scheduled recycling week
var demarcationdate = new Date("March 13, 2017 00:00:00"); // start date based on previously scheduled recycling week
    showTodaysDate = document.getElementById('todaysDate'),
    showNeighborhood = document.getElementById('neighborhood'),
    showFutureDate = document.getElementById('futureDate'),
    nextWeekBegins = document.getElementById('followingWeek'),
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    today = new Date(),
    days = daysBetween(demarcationdate,today),
    daystill = 14 - days%14,
    rec = days%14==0,
    d = new Date();

// add remaining days to current date to get next recycling week start date
d.setDate(today.getDate() + daystill); 

// format dates to make them easy to read
var currentDate = (dayNames[today.getDay()] + ", " +  monthNames[today.getMonth()] + " " +  today.getDate() + ", " +  today.getFullYear());
var nextDate = (monthNames[d.getMonth()] + " " +  d.getDate());

// show current date, always on
showTodaysDate.innerHTML="Today is "+currentDate.toString()+", and "; 

// show start date of next recycling week and days remaining, always on
nextWeekBegins.innerHTML="The next recycling week begins " + dayNames[d.getDay()] + ", " + nextDate.toString() + " ("+daystill+" days from now)."



// Conditional display rules
var date1 = new Date(today); // today's date
var date2 = new Date(d); // day next recycling week starts
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // caluclate time between two dates
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // convert that time to days


if (diffDays <= 7) { 
// if (rec === true) { // ignore this, it's just to test 'showNeighborhood'
  // if it is not a recycling week, show the start date of the following recycling week
  showFutureDate.innerHTML="there is <strong>no recycling pickup</strong> scheduled this week."; 

} else {
  // if it is a recycling week, show scheduled neighborhood
  showNeighborhood.innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].neighborhood + " (excluding holidays). "; 
}
//基于时间的问候语
var thehours=新日期().getHours();
var greeting=document.getElementById('greeting');
var消息;
var morning=(“早上好!”);
var午后=(‘下午好’);
晚上好(‘晚上好’);
如果(小时数>=0&&小时数<12){
themessage=早晨;
}否则如果(小时数>=12和小时数<17){
themessage=下午;
}否则如果(小时数>=17和小时数<24){
themessage=晚上;
}
greeting.innerHTML=themessage;//显示问候语,始终打开
//星期一的邻居
var scheduleCurrentDate=新日期();
var scheduleAllDays=[
{
日:“星期日”,
邻里区:“计划在费尔蒙特邻里区进行回收利用”“,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Sunday+“图像”
},
{
日期:“星期一”,
邻里区:“计划在西市场邻里区进行回收利用”“,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Monday+“图像”
},
{
日期:“星期二”,
邻里区:“联合街邻里区计划进行回收利用”“,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Tuesday+“图像”
},
{
日:“星期三”,
邻里:“百老汇和州立街邻里将安排回收车”,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Wednesday+“图像”
},
{
日期:“星期四”,
邻里区:“计划在市中心邻里区进行回收利用”“,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Thursday+“图像”
},
{
日期:“星期五”,
社区:“计划在东山社区进行回收。”,
图片:
"https://via.placeholder.com/1920x1080/555555/666666/?text=Friday+“图像”
},
{
日期:“星期六”,
邻里区:“计划在肯迪塞格邻里区进行回收利用”“,
图片:
"https://via.placeholder.com/450x800/555555/666666/?text=Saturday+“图像”
}
];
//document.getElementById(“day”).innerHTML=scheduleAllDays[scheduleCurrentDate.getDay()].day;
//document.getElementById(“邻里”).innerHTML=scheduleAllDays[scheduleCurrentDate.getDay()]邻里+“(不包括节假日)。”;
document.getElementById(“map”).style.background=
“url(“+scheduleAllDays[scheduleCurrentDate.getDay()]”image+“)无重复中心”;//根据星期几显示背景图像
//计算双周计划
功能治疗ASUTC(日期){
var结果=新日期(日期);
result.setMinutes(result.getMinutes()-result.getTimezoneOffset());
返回结果;
}
函数日期之间(开始日期、结束日期){
var毫秒Sperday=24*60*60*1000;
返回数学地板((处理时间(结束日期)-处理时间(开始日期))/毫秒/天);
}
//基于最近计划的回收周的开始日期
var标定日期=新日期(“2017年3月13日00:00:00”);//基于先前计划的回收周的开始日期
showTodaysDate=document.getElementById('todaysDate'),
showNeighborary=document.getElementById('Neighborary'),
showFutureDate=document.getElementById('futureDate'),
nextWeekBegins=document.getElementById('followerweek'),
monthNames=[“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],
dayNames=[“星期日”、“星期一”、“星期二”、“星期三”、“星期四”、“星期五”、“星期六”],
今天=新日期(),
天=日之间(分界日期,今天),
DayStall=14-天数%14,
rec=天数%14==0,
d=新日期();
//将剩余天数添加到当前日期,以获取下一个回收周开始日期
d、 setDate(今天.getDate()+DayStall);
//设置日期格式,使其易于阅读
var currentDate=(dayNames[today.getDay()]+,“+monthNames[today.getMonth()]+”“+today.getDate()+”,“+today.getFullYear());
var nextDate=(monthNames[d.getMonth()]+“”+d.getDate());
//显示当前日期,始终打开
showTodaysDate.innerHTML=“今天是”+currentDate.toString()+”,和”;
//显示下一个回收周的开始日期和剩余天数,始终打开
nextWeekBegins.innerHTML=“下一个回收周开始”+dayNames[d.getDay()]+,“+nextDate.toString()+”(“+daystill+”从现在开始的几天)
//条件显示规则
var date1=新日期(今天);//今天的日期
var date2=新日期(d);//下一个回收周开始
var timeDiff=Math.abs(date2.getTime()-date1.getTime());//计算两个日期之间的时间
var diffDays=Math.ceil(timeDiff/(1000*3600*24));//将该时间转换为天
如果(如果)你的应用程序运行了几天
// greeting based on time of day
var thehours = new Date().getHours();
var greeting = document.getElementById('greeting');
var themessage;
var morning = ('Good morning!');
var afternoon = ('Good afternoon!');
var evening = ('Good evening!');

if (thehours >= 0 && thehours < 12) {
  themessage = morning; 

} else if (thehours >= 12 && thehours < 17) {
  themessage = afternoon;

} else if (thehours >= 17 && thehours < 24) {
  themessage = evening;
}

greeting.innerHTML= themessage; // show greeting, always on


// neighborhood for day of week
var scheduleCurrentDate = new Date();
var scheduleAllDays = [
  {
    day: "Sunday",
    neighborhood: "recycling pickup is scheduled for the <strong>Fairmount Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Sunday+Image"
  },
  {
    day: "Monday",
    neighborhood: "recycling pickup is scheduled for the <strong>West Market Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Monday+Image"
  },
  {
    day: "Tuesday",
    neighborhood: "recycling pickup is scheduled for the <strong>Union Street Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Tuesday+Image"
  },
  {
    day: "Wednesday",
    neighborhood: "recycling pickup is scheduled for the <strong>Broadway and State Street Neighborhoods</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Wednesday+Image"
  },
  {
    day: "Thursday",
    neighborhood: "recycling pickup is scheduled for the <strong>Downtown Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Thursday+Image"
  },
  {
    day: "Friday",
    neighborhood: "recycling pickup is scheduled for the <strong>East Hills Neighborhood</strong>",
    image:
    "https://via.placeholder.com/1920x1080/555555/666666/?text=Friday+Image"
  },
  {
    day: "Saturday",
    neighborhood: "recycling pickup is scheduled for the <strong>Kenduskeag Neighborhood</strong>",
    image:
    "https://via.placeholder.com/450x800/555555/666666/?text=Saturday+Image"
  }
];

// document.getElementById("day").innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].day;
// document.getElementById("neighborhood").innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].neighborhood + " (excluding holidays). ";
document.getElementById("map").style.background =
  "url('" + scheduleAllDays[scheduleCurrentDate.getDay()].image + "') no-repeat center"; // show background image, based on day of the week



// calculate bi-weekly schedule
function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return Math.floor((treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay);
}

// start date based on most recently scheduled recycling week
var demarcationdate = new Date("March 13, 2017 00:00:00"); // start date based on previously scheduled recycling week
    showTodaysDate = document.getElementById('todaysDate'),
    showNeighborhood = document.getElementById('neighborhood'),
    showFutureDate = document.getElementById('futureDate'),
    nextWeekBegins = document.getElementById('followingWeek'),
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    today = new Date(),
    days = daysBetween(demarcationdate,today),
    daystill = 14 - days%14,
    rec = days%14==0,
    d = new Date();

// add remaining days to current date to get next recycling week start date
d.setDate(today.getDate() + daystill); 

// format dates to make them easy to read
var currentDate = (dayNames[today.getDay()] + ", " +  monthNames[today.getMonth()] + " " +  today.getDate() + ", " +  today.getFullYear());
var nextDate = (monthNames[d.getMonth()] + " " +  d.getDate());

// show current date, always on
showTodaysDate.innerHTML="Today is "+currentDate.toString()+", and "; 

// show start date of next recycling week and days remaining, always on
nextWeekBegins.innerHTML="The next recycling week begins " + dayNames[d.getDay()] + ", " + nextDate.toString() + " ("+daystill+" days from now)."



// Conditional display rules
var date1 = new Date(today); // today's date
var date2 = new Date(d); // day next recycling week starts
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // caluclate time between two dates
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // convert that time to days


if (diffDays <= 7) { 
// if (rec === true) { // ignore this, it's just to test 'showNeighborhood'
  // if it is not a recycling week, show the start date of the following recycling week
  showFutureDate.innerHTML="there is <strong>no recycling pickup</strong> scheduled this week."; 

} else {
  // if it is a recycling week, show scheduled neighborhood
  showNeighborhood.innerHTML = scheduleAllDays[scheduleCurrentDate.getDay()].neighborhood + " (excluding holidays). "; 
}