JS How to keep counting the time - javascript

I just started learning Javascript a month ago. I would like to know how to keep counting and updating and showing it in real-time.
var date = new Date();
var second = document.querySelector('#sec')
var time = document.querySelector('#future-time')
function currentTime(){
console.log('a')
time.innerHTML = date;
second.innerHTML = date.getSeconds();
}
setInterval(currentTime, 1000);
with this code, I can see the time on the page but then, the second doesn't update so it keeps saying the same second with console.log(). The current time on the page doesn't go forward. Please help me.

The issue you're running in to is that once you assign var date = new Date() then date will always be the datetime as of that exact time it was assigned. You can instead create a new Date object each time you call currentTime and you'll get a refreshed Date object current as of the time the function is called.
var second = document.querySelector('#sec')
var time = document.querySelector('#future-time')
function currentTime(){
var date = new Date();
time.innerHTML = date;
second.innerHTML = date.getSeconds();
}
setInterval(currentTime, 1000);
<span id="sec"></span>
<span id="future-time"></span>

Related

Time changes after toLocaleTimeString()

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.
Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

I can't get current millisecond in Javascript

I can't get updated (current) time as milliseconds below. Even if I reassign the system time inside of the loop, the functionality does not work as I aimed. I'm kinda new about using JavaScript. So I was trying to convert below Java code to JavaScript. What is the problem in my JS code could you help me please?
My purpose with this function: Make system wait until the value becomes not null
Current result -> Time difference does not change per given check interval
waitUntilValueComes(value, timeout, checkInterval) {
let currentTime = new Date().getMilliseconds()
cy.log('Current time ' + currentTime)
let diff = new Date().getMilliseconds()- currentTime
while (timeout > (diff)) {
cy.log('Date time ' + diff)
if (value != null) {
break
}
cy.wait(checkInterval)
diff = new Date().getMilliseconds()- currentTime
}
}
Java Code that I tried to transform into JS
public void waitUntilValueComes(String value, long timeout, long checkInterval) throws InterruptedException {
long currentTime = System.currentTimeMillis();
while (timeout > System.currentTimeMillis() - currentTime) {
if (value!= null)
break;
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(checkInterval));
}
}
You can try the Date.now() Global object and method which gets the current time with milliseconds but in unix timestamp however its a little inaccurate compared to the 2nd method in firefox browsers as per the MDN Docs
The first method is what you need if you need the time stamp
The second method is the same as the method you used
Just assign a new const newDate = new Date();
Call that const with .getMilliseconds() method
assign that to a new const dateMS = newDate.getMilliseconds();
Debug the dateMS variable we just assignedconsole.log(dateMS);
const dateNow = Date.now();
console.log("dateNow is:" + dateNow);
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
//FOR YOUR OLD METHOD JUST ASSIGN A VARIABLE for the new date
const newDate = new Date();
const dateMS = newDate.getMilliseconds();
console.log("Date in milli seconds is" + dateMS);
W3School JavaScript Date Methods

How do I add 1 to a date in a query string with an onClick function?

I am trying to have previous day, current day, and next day buttons so for example, if I press the next button, it will take today's date, add one to today's date and show tomorrows information on the page.
My click handler looks like:
const nextHandler = () => {
let resDate = new Date();
let year = resDate.getFullYear();
let day = new Date().getDate();
let month = resDate.getMonth() + 1;
if (month.toString().length < 2 || day.toString().length < 2) {
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
}
day = parseInt(day) + 1;
let newDate = `${year}-${month}-${day}`;
// newDate --> 2021-04-11
history.push(`/dashboard?date=${newDate}`);
};
When I click my next button I get taken to: http://localhost:5000/reservations?date=2021-04-12 exactly as I would like. However, I am only able to add to the day once. How am I continuously able to update this query string?
You're only ever starting with new Date(); on your second line so it'll only ever increment once. You'll have to read from the querystring a value to put in new Date(VALUE); if it's set so that it continues to remember. Here's a stackoverflow answer from something like that: How can I get query string values in JavaScript?
You're code may look like:
const urlParams = new URLSearchParams(window.location.search);
const dateParam = urlParams.get('date');
let resDate = dateParam ? new Date(dateParam) : new Date();
It's nextHandler is using today's date to increment rather than the date of the query string.
On the first click, nextHandler today's date to increment. But, the next click should start from the date in the query string.
I hope that solve your problem.

Make a date/time value called from an API tick very second. (JavaScript)

I'm calling a date and time through an API, which looks like this:
<?php $xml = simplexml_load_file("https://api.eveonline.com/server/ServerStatus.xml.aspx/"); ?>
<div class="server-time">
<?php echo $xml->currentTime; ?>
</div>
This will show a date and time like this on the page:
2013-10-16 08:15:36
Now I want this clock to tick every second and the time and even date (in case it's just seconds before midnight when the user visits the site) values to change accordingly, just like you would expect a digital clock to work.
I know this is possible with JavaScript but since I am a total rookie at it I don't know how to do this - at all.
Help would be highly appriciated!
There are many javascript clocks out there, you don't even have to use an API to get the time and date!
function clock(id) {
//Create a new Date object.
oDate = new Date();
//Get year (4 digits)
var year = oDate.getFullYear();
//Get month (0 - 11) - NOTE this is using indexes, so 0 = January.
var month = oDate.getMonth();
//Get day (1 - 31) - not using indexes.
var day = oDate.getDate();
//Get hours
var hours = oDate.getHours();
//Get minutes
var minutes = oDate.getMinutes();
//Get seconds
var seconds = oDate.getSeconds();
//Maybe create a function that adds leading zero's here
var dateStr = '';
dateStr += year+' - '+month+' - '+day+' '+hours+':'+minutes+':'+seconds;
//Append dateStr to some element.
document.getElementById(id).innerHTML = dateStr;
//Repeat the function every 1000 miliseconds aka 1 second
setTimeout(function() {
clock(id);
}, 1000);
}
The usage would be
<div id="yourID">clock input will go here</div>
clock('yourID');
NOTE
This function has to be called after the DOM is loaded, otherwise this would result in error.
This can be achieved by placing the script tag with your JS at the bottom of the page (not using jQuery that is).
Otherwise if using jQuery, call the $(function() {}) (equivelant to $(document).ready(function() {});
The function is quite self-explanatory, but maybe you would want to read up on the functions to see exactly what they do.
a quick google search should do the trick.
Anyways hope this helps, good luck :)
I'm not sure if you want it to fetch the time from the api every second or, if you want it to just increase every second, starting from the given api time. In the latter case, you should use setInterval:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = $('.server-time').text();
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
$('.server-time').text(date.toString());
}
setInterval(updateTime, 1000);
If you are not using jquery, just use document.getElementById or something like that:
change your element to:
<div id="server-time">
and use the following snippet:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = document.getElementById('server-time').innerHTML;
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
document.getElementById('server-time').innerHTML = date.toString();
}

How to add one second to a time string with javascript/jquery

I am trying to create a timer with Javascript but I don't know how to add one second to a time string.
Time string: 03:31:15
function updateWorked() {
var time = $("#worked").html();
???
$("#worked").html(wtime);
}
$(document).ready(function() {
setInterval('updateWorked()', 1000);
});
What should I write in "???" to make this work?
Assuming you are using something like PHP to get the time string in the first place, and you can't keep track of the date/time as a number as suggested by Marc B, you can parse the string yourself like this:
var $worked = $("#worked");
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(ss[0]);
dt.setMinutes(ss[1]);
dt.setSeconds(ss[2]);
var dt2 = new Date(dt.valueOf() + 1000);
var ts = dt2.toTimeString().split(" ")[0];
$worked.html(ts);
Edit: Working jsFiddle here of this code.
Here's the code with a timer: jsFiddle
Below is an example on how to add a second to a time string. You can use the date object to print out the string in any format that you would like, in this example i'm just using the build in toTimeString method.
var timeString = "10/09/2012 14:41:08";
// start time
var startTime = new Date(timeString);
// prints 14:41:08 GMT-0400 (EDT)
console.log(startTime.toTimeString())
// add a second to the start time
startTime.setSeconds(startTime.getSeconds() + 1);
// prints 14:41:09 GMT-0400 (EDT)
console.log(startTime.toTimeString())
If you're trying to keep a counter in real time, you should use new Date() to get the time, and then format it:
function updateWorked() {
var time = new Date(),
wtime = formatDate(time);
$("#worked").html(wtime);
}
However, if you're trying to keep a specific time, then you should up-scope a Date object and use that:
var time = new Date(/* your starting time */);
function updateWorked() {
time.setTime(time.getTime()+1000);
var wtime = formatDate(time);
$("#worked").html(wtime);
}
Also, you'd want to add a formatDate function:
function formatDate(date) {
var hours = date.getHours().toString();
if (hours.length < 2) hours = '0'+hours;
var minutes = date.getMinutes().toString();
if (minutes.length < 2) minutes = '0'+minutes;
var seconds = date.getSeconds().toString();
if (seconds.length < 2) seconds = '0'+seconds;
return hours+':'+minutes+':'+seconds;
}
Using mixture of jquery and javascript you can achieve this example.
I tired to achive what you looking for, first created a date object and get all the values of time, minute and second and then replaced the value.
Please have a look at jsfiddle
DEMO
http://jsfiddle.net/saorabhkr/xtrpK/

Categories

Resources