I have been trying to get my page to refresh at midnight, but the code I wrote is not working.
This is the code that I have written:
function reloadClock() {
var reloadTime = new Date();
var hrs = reloadTime.getHours();
var min = reloadTime.getMinutes();
var sec = reloadTime.getSeconds();
// I tried this code, it will not work.
if (hrs == 0 && min == 0 && sec == 0) {
alert('this page will now reload');
location.reload();
}
// I also tried this code, still can't get it to work.
if (hrs == 14) { // Works as intended.
alert(hrs);
if (min == 31) { // Works as intended.
alert(min);
if (sec == 0) { // Does not work as intended.
alert(sec);
location.reload();
}
}
}
setTimeout(reloadClock(), 1000);
}
Does anyone know a solution for this?
check this
const timerefresh = setInterval(function(){
const time_ = new Date().toLocaleString('en-GB'); // return 24 hour time format in string, explaination about en-GB you can search on wikipedia, thats bored (:
let date = time_.split(', ')[0].split('/'); // split the time strings to get date in array [day, month, year]
let clock = time_.split(', ')[1].split(':'); // split the time strings to get clock in array [hour, min, sec]
countDownTime(Number(clock[0]),Number(clock[1]),Number(clock[2]));
document.getElementById('time1').innerHTML = 'date:'+date+', clock:'+clock;
},1000);
function countDownTime(h,m,s){
// some match to reverse the clock
document.getElementById('time2').innerHTML = 'countdown to midnight : '+ (23-h)+':'+(59-m)+':'+(60-s);
if(h === 23 && m === 59 && s === 59){ itsMidnight(); } // call its midnight 1 sec before clock 00:00:00
}
function itsMidnight(){
// its midnight, your function here
console.log('midnight! reload.')
window.location.reload();
}
// code below just for testing, you can delete it
let sectomidnight = 50;
function gotoMidnight(){
clearInterval(timerefresh);
setInterval(function(){
sectomidnight += 1;
countDownTime(23,59,sectomidnight);
},1000);
}
<div id="time1"></div>
<div id="time2"></div>
<button onclick="gotoMidnight();">goto 10 sec before midnight</button>
Related
I have created a web based clock using javaScript. it outputs time in 12 hour format and needs to be refreshed pressing F5 whenever clock ticks 12 AM or 12 PM.
So i need a program to refresh the webpage automatically whenever the clock ticks 12 AM or PM .
I was checking my JS clock the output was
Output: 11: 59 : 00 PM Sunday // 23 : 59 : 00
After few minutes I checked again
Output 12 : 01 : 00 PM Sunday // 0 : 01 : 00
I had to refresh webpage to see changes
I want auto refresh program
Here is my code
<body onload="autoref()">
<script>
function autoref(){
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
if(h==0 && s==0){
location.reload();
}else if(h==12 && s==0){
location.reload();
}
var trig = setTimeout(autoref,500);
}
</script>
</body>
Any ideas!?
Thanks
Without seeing any of your code this is the best I can offer.
var amPm = undefined
function drawDisplay () {
// code that draws your display
}
setInterval(()=>{
var hour = (new Date()).getHours()
if (hour === 0 && amPm !== 'am') {
amPm = 'am'
drawDisplay ()
}
if (hour === 12 && amPm !== 'pm') {
amPm = 'pm'
drawDisplay ()
}
},1000)
Another way
// code that draws your display
function drawDisplay() {
var seconds = -1
return ()=>{
var date = new Date()
if (date.getSeconds() > seconds || (date.getSeconds() === 0 && seconds === 59)) {
seconds = date.getSeconds()
console.log(date.toLocaleString())
}
}
}
setInterval(drawDisplay(),250)
As you have mentioned "whenever", i take it that it must happen every day and have added code to check whether page is refreshed, to avoid continuous refresh.
Here is the code:
Remember to accept the answer and click the upvote button if the answer satisfies you,
else give more information in the question (like, what have you done and then what are you getting), so that members here, can give right answers.
Also don't get demotivated with negative comments by experienced ones.
<span id='spn'>
</span>
<script
src='https://code.jquery.com/jquery-3.3.1.min.js'
integrity='sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8='
crossorigin='anonymous'></script>
<script>
//variable to check whether the page was refreshed or the page will keep on refreshing every second.
var vrefreshed=localStorage.getItem('refreshed');
if (typeof vrefreshed === 'undefined')
vrefreshed = 0;
function time() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(vrefreshed==0 && ((h==23 && m==59 && s==59) || (h==11 && m==59 && s==59))){
localStorage.setItem('refreshed', 1);
vrefreshed=1;
$('#spn').text('page is refreshed.');
location.reload();
}else{
if(vrefreshed==1 && ((h==23 && m==59 && s==59) || (h==11 && m==59 && s==59))){
// do nothing
}else{
localStorage.setItem('refreshed', 0);
vrefreshed=0;
$('#spn').text('page will be refreshed at 12 or 24.');
}
}
}
//call time() function every 1000 milliseconds i.e. every second.
setInterval(time, 1000);
</script>
I have got answer myself sorry for disturbing you guys
Heres my code
<body onload="refresh()">
<h1>
Hello, Dcoder
</h1>
<div class="dcoder">
</div>
<script>
function refresh(){
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var out = h+" : "+m+" : "+s;
var trig = setTimeout(refresh,500);
document.getElementsByClassName("dcoder")[0].innerHTML = out;
if(h==12 && s==0){
location.reload();
}else if(h==0 && s==0){
location.reload();
}
}
</script>
</body>
</html>
i need to compare two values and do stuff with the result of the comaprison depending on if the times are more than 1 hour apart.
So for example
Time1 = 13:07:01
Now = 13:26:47
what i need to do is in an if statement compare to see if Now is an hour ahead of Time one for example
If( Comparison){
1 hour has passed
}else{
1 hour has not passes
}
What would be the best way to do this?
Use Date() - MDN
if (Date.now() > new Date(oldDate) + 1000 * 60 * 60) {
console.log('1 hour has passed');
} else {
console.log('1 hour has not passed');
}
<script>
function checkForOneHr(){
var start = '5:30';
var end = '6:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
if(hour >= 1)
return true;
else
return false;
}
if( checkForOneHr()){
alert('1 hour has passed');
}else{
alert(' hour has not passes ');
}
</script>
If they are Date objects
var now = new Date();
var diff = now.getTime() - time1.getTime();
if(diff >= 1000*60*60) {
console.log('an hour has passed');
} else {
console.log('an hour has not passed');
}
First of All , Convert Both the times to string format using,
strtotime().
See any PHP manual.
Take out the difference of them.
The result will be difference in seconds.
Divide the difference by 3600.
If it is greater then 1, do your 'Code to do".
eg.
$current_time = date('T-m-d H:I:S');
$time_now = strtotime($current_time);
I have an issue where I want to check the time and do something based on it. For example, from 12 midnight to 1 am, I would like to stop the page from refreshing. How would I accomplish this?
function RefreshPage()
{
if (refresh == 'Y')
{
CheckAndStopAutoRefresh();
}
}
function CheckAndStopAutoRefresh()
{
var d = new Date();
var currentHour = d.getHours(); // 0-23
if (currentHour >= 0 && currentHour < 1)
{
return;
}
else
{
window.location=window.location; // refresh
}
}
//initialize date object
var d = new Date();
var currentHour = d.getHours(); //note 0-23
//you could use currentHour == 0 but this expression allows for a range
if (currentHour >= 0 && currentHour < 1)
{
console.log('between 0:00 and 1:00 hrs');
}
else { console.log('after 1am'); }
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date provides and overview of the date object
I am not too sure what you mean by 'stop refresh' I do not believe it possible to disable refresh/F5, but perhaps if you modify your question or specify your intentions I can take another stab at the question.
EDITED
--edited to reflect updated question.
I would use setInterval(code,millisec,lang)
function CheckAndStopAutoRefresh() {
//initialize date object
var d = new Date();
var currentHour = d.getHours(); //note 0-23
//you could use currentHour == 0 but this expression allows for a range
if (currentHour >= 0 && currentHour < 1)
{
console.log('between 0:00 and 1:00 hrs');
}
else { console.log('after 1am'); }
}
setInterval(CheckAndStopAutoRefresh,60000); //60,000 milliseconds in a minute
I'm displaying a message between Saturday at 6pm and Sunday 4am. The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});
Why do you even need that UTC stuff? Just work with local time:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}
This should get you your server's time:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; it's the hours. It may need to be a -5; I'm not really sure.
Also, that's going to break every daylight savings. You'll have to detect that somehow and modify serverOffset.
What I am currently doing is setting up a calendar feature, but when the user selects the date, and then the TIME the event starts (ie startTime = 00:10:00am), that it will then pre-populate the second field (ie: endTime = 00:10:30am).
So I thought maybe the best route would be when you select your time, jQuery would just select the NEXT statement and pick up the 15 minute interval or something of this nature.
I have this code that works to select the exact same time, but that doesn't work well for scheduling obviously, if you select 10am, you don't want your end time to be 10am, you want it to be 10:30am
This is what I have so far, but like I say this just currently selects the same time.
$('.startTime').change(function() {
var startTime = $(this).val();
$('.endTime').val(function() {
return startTime;
});
});
Any guidance would be appreciated.
You'd need to convert startTime into a proper js Date object, then do something like this. If you're using a JS framework, there might already be some utils in place to do this.
This is what works, I don't know if it is efficient or not, but I got this to work. If there is a better answer, I'm all ears.
$('.startTime').change(function() {
var startTime = $(this).val();
var hours = startTime.split(":")[0]; // Hours
var minutes = startTime.split(":")[1]; // Minutes
var seconds = startTime.split(":")[2]; // Seconds
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var newTime = new Date('0', '0', '0', hours, minutes, seconds, '0');
//alert(newTime.getMinutes());
if(newTime.getMinutes() == '15' || newTime.getMinutes() == '00') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '30') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '45') {
finalTime = newTime.setHours(newTime.getHours() + 1, 0);
}
if(newTime.getHours() < 10) {
newHours = '0'+ newTime.getHours();
} else {
newHours = newTime.getHours();
}
if(newTime.getMinutes() < 10) {
newMinutes = '0'+ newTime.getMinutes();
} else {
newMinutes = newTime.getMinutes();
}
if(newTime.getSeconds() < 10) {
newSeconds = '0'+ newTime.getSeconds();
} else {
newSeconds = newTime.getSeconds();
}
var adjustTime = newHours +":"+ newMinutes +":"+ newSeconds;
$('.endTime').val(function() {
return adjustTime;
});
});