How To Change The Value Of A Variable Once Per Day In Java/javascript
I'm trying to make an application/script for my school which displays the day's schedule. The catch with this is that my school runs on an 8 day cycle, so that complicates things.
Solution 1:
You can use, say, the getTime()
function of the Date
object, which returns the current time in milliseconds after January 1, 1970 (source: http://www.w3schools.com/jsref/jsref_gettime.asp), and save that value (e.g. in var lastUpdateTime
). Then periodically check if the difference between the current time and that saved time is more than a day. If so, update cycleDay, and also update lastUpdateTime
to the time when you updated.
For instance, initialize with:
var lastUpdateTime = newDate().getTime();
Somewhere else in your code:
var currentTime = newDate().getTime();
if(currentTime - lastUpdateTime >= 24*60*60*1000) // number of milliseconds in a day
{
// update cycleDay
lastUpdateTime = currentTime;
// ...
}
Solution 2:
privateDate lastUpdate = now()-1;
private myDailyChahgedValue;
IntegergetMyDailyChangedValue() {
if (lastUpdate <> now()) {
myDailyChahgedValue ++;
}
return value;
}
Please note it is an a draft of code what shows main idea
Solution 3:
Use Date
and document.cookies
to update your variable. Also i used two utility methods to manipulate document.cookies
var today = parseInt(newDate().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 */functionsetCookie(name, value, daysToLive) {
var cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number")
cookie += "; max-age=" + (daysToLive*60*60*24);
document.cookie = cookie;
}
functiongetCookies() {
var cookies = {}; // The object we will returnvar all = document.cookie; // Get all cookies in one big stringif (all === "") // If the property is the empty stringreturn cookies; // return an empty objectvar list = all.split("; "); // Split into individual name=value pairsfor(var i = 0; i < list.length; i++) { // For each cookievar cookie = list[i];
var p = cookie.indexOf("="); // Find the first = signvar name = cookie.substring(0,p); // Get cookie namevar 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 */
Post a Comment for "How To Change The Value Of A Variable Once Per Day In Java/javascript"