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/
Related
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>
I am using Moment library in Javascript
I would like to add time, so I tried:
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = time1.add(time2);
let format = moment.utc(add).format("HH:mm:ss")
console.log(format);
I will expected my format will be 10:03:15 but turns out it gave me 18:03:15
I wonder why it add another 8 hours for me, well considered as .utc problem, I try to perform without .utc as follows:
let format = moment(add).format("HH:mm:ss")
It return 02:03:15.
It kinda frustrated I dunno what is happening
*By the way
var add1 = time3.add(5588280, 'ms');
*it works fine by adding with h, m, s, ms to it
Ciao, with moment add you could add time in 3 ways:
moment().add(Number, String);
moment().add(Duration);
moment().add(Object);
This is the version moment().add(Number, String);
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = moment(time1).add(time2.minutes(), "minutes").add(time2.seconds(), "seconds");
let format = add.format("HH:mm:ss");
console.log(format); // without utc
let formatUtc = moment.utc(add).format("HH:mm:ss");
console.log(formatUtc); // with utc
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
This is the version moment().add(Object);
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = moment(time1).add({minutes: time2.minutes()}).add({seconds: time2.seconds()});
let format = add.format("HH:mm:ss");
console.log(format); // without utc
let formatUtc = moment.utc(add).format("HH:mm:ss");
console.log(formatUtc); // with utc
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
You already know the third version :)
add is the two-argument function with the need first argument as the number and second argument is number type in time laps.
i.e it is working with microseconds
time3.add(5588280, 'ms')
Here you can do for your problem
const time1 = moment("10:00:00", "HH:mm:ss");
const time2 = moment("00:03:15", "HH:mm:ss");
// get hours from time2 and add in time1
const add = time1.add(time2.format('mm'), 'hours')
// add minutes using chain
.add(time2.format('mm'), 'minutes')
// add seconds using add method from moment
.add(time2.format('ss'), 'seconds');
const format = moment(add).format("HH:mm:ss")
By using UTC on the moment it converts time into UTC and format make it as
time string format
moment(add).format("HH:mm:ss")
// Your required time:- 13:03:15
moment.utc(add).format("HH:mm:ss")
// required time in UTC:- 07:33:15
You can simply use moment duration function to add two times together we do not use to use extra lines code (like minutes, seconds, or hours) here to get the results you want.
Just add two times with duration and get them as milliseconds and then format them as you like to.
Live Demo:
let time1 = "10:00:00"; //string
let time2 = "00:03:15"; //string
let addTwoTimes = moment.duration(time1).add(moment.duration(time2)) //add two times
let format = moment.utc(addTwoTimes.as('milliseconds')).format("HH:mm:ss") //format
console.log(format); //10:03:15
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>
I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp
I want time duration between two date time. I have the start date, start time, end date and end time. Now I have to find the difference between them.
Actually I have tried with this following code, but I got the alert like 'invalidate date'.
function myfunction()
{
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var new_st_dt=new Date(start_dt);
var new_end_dt=new Date(end_dt);
alert('new_st_dt:'+new_st_dt);
alert('new_end_dt:'+new_end_dt);
var duration=new_end_dt - new_st_dt;
alert('duration:'+duration);
}
the alert msg like as follows:
new_st_dt:invalid date
new_end_dt: invalid date
duration:NaN
when I run in android simulator I got these alert messages.
Please help me how to get it? How to implement this?
You're passing an invalid ISO date string to that Date() constructor. It needs a form like
YYYY-MM-DDThh:mm:ss
for instance
2013-10-29T10:10:00
So you basically forgot the T to separate date and time. But even if the browser reads in the ISO string now, you would not have an unix timestamp to calculate with. You either can call
Date.parse( '2013-10-29T10:10:00' ); // returns a timestamp
or you need to explicitly parse the Date object, like
var duration=(+new_end_dt) - (+new_st_dt);
Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Try formatting you timestamps as isoformat so javascript recognizes them. (you put a "T" between the date and time). An example: '2013-10-29T10:10:00'
function dateDiff(){
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var d1= start_dt ;
d1.split("-");
var d2= end_dt ;
d2.split("-");
var t1 = new Date(d2[0],d2[1],d2[2]);
var t2 = new Date(d1[0],d1[1],d1[2]);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
return Math.abs(Seconds_from_T1_to_T2);
}
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();
}