如何在Java/javascript中每天更改一次变量的值

How to change the value of a variable once per day in Java/javascript

本文关键字:一次 变量 Java javascript 每天      更新时间:2023-09-26

我正在为我的学校制作一个显示当天时间表的应用程序/脚本。这样做的问题是,我的学校是以8天为一个周期的,所以事情变得复杂了。我有一个名为cycleDay的变量,但我该如何每天更新一次,而不是更多?如果你还有其他方法可以考虑的话,请告诉我。

谢谢!

您可以使用Date对象的getTime()函数,该函数返回1970年1月1日之后的当前时间(以毫秒为单位)(来源:http://www.w3schools.com/jsref/jsref_gettime.asp),并保存该值(例如,在var lastUpdateTime中)。然后定期检查当前时间和保存的时间之间的差异是否超过一天。如果是,请更新cycleDay,并将lastUpdateTime更新到更新时的时间。

例如,初始化时使用:

var lastUpdateTime = new Date().getTime();

代码中的其他位置:

var currentTime = new Date().getTime();
if(currentTime - lastUpdateTime >= 24*60*60*1000) // number of milliseconds in a day
{
    // update cycleDay
    lastUpdateTime = currentTime;
    // ...
}
private Date lastUpdate = now()-1;
private myDailyChahgedValue;
Integer getMyDailyChangedValue() {
 if (lastUpdate <> now()) {
  myDailyChahgedValue ++;
}
return value;
}

请注意,这是一份代码草案,显示了的主要思想

使用Datedocument.cookies更新变量。此外,我还使用了两种实用方法来操作document.cookies

var today = parseInt(new Date().getTime()/(1000*3600*24))
var cookies = getCookies();
if(cookies["last_updated"] && cookies["last_updated"]<today) 
{
    /* update variable */
    setCookie("last_updated", today, 1);
}
/* utility methods starts, adding utility methods to simplify setting and getting    cookies  */
function setCookie(name, value, daysToLive) {
   var cookie = name + "=" + encodeURIComponent(value);
   if (typeof daysToLive === "number")
      cookie += "; max-age=" + (daysToLive*60*60*24);
   document.cookie = cookie;
 }
function getCookies() {
    var cookies = {}; // The object we will return
    var all = document.cookie; // Get all cookies in one big string
    if (all === "") // If the property is the empty string
       return cookies; // return an empty object
    var list = all.split("; "); // Split into individual name=value pairs
    for(var i = 0; i < list.length; i++) { // For each cookie
       var cookie = list[i];
       var p = cookie.indexOf("="); // Find the first = sign
       var name = cookie.substring(0,p); // Get cookie name
       var value = cookie.substring(p+1); // Get cookie value
       value = decodeURIComponent(value); // Decode the value
       cookies[name] = value; // Store name and value in object
  }
  return cookies;
}
/* utility methods ends */