I have two times (basically start time and end time). Also, I have the number of questions played by the user. I wanna know the average time user spent for each question.
//startGameTime: 2019-07-27T07:58:42.000Z
//endGameTime: 2019-07-27T07:59:57.000Z
function averageQuestionTime(startGameTime, endGameTime, totalNumberOfQuestions) {
var d1 = new Date(startGameTime);
var d2 = new Date(endGameTime);
var d1msecs = new Date(d1).getTime(); // get milliseconds
var d2msecs = new Date(d2).getTime(); // get milliseconds
var avgTime = (d1msecs + d2msecs) / totalNumberOfQuestions;
var date = new Date(avgTime);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
return (day + ":" + hour + ":" + min + ":" + sec)
}
I understand my logic is completely flawed as the units for date and time and nos of questions are different. What is the best way to achieve the result ?
There are good libraries which prevent the users from having to reinvent the wheel every time they want to manipulate date/time in Node.
Obtaining time difference is pretty simple (I can see you are doing it correctly to obtain the difference in milliseconds) and libraries make them even simpler.
See how simple it is using momentJS
var moment = require('moment');
var startDate = moment('2019-7-24 00:00:00', 'YYYY-M-DD HH:mm:ss');
var endDate = moment('2019-7-24 05:27:31', 'YYYY-M-DD HH:mm:ss');
var diffSeconds = endDate.diff(startDate, 'seconds');
var diffHours endDate.diff(startDate, 'seconds');
console.log(`Avg in secs: ${diffSeconds / totalNumberOfQuestions}`);
console.log(`Avg in secs: ${diffHours/ totalNumberOfQuestions}`);
I'm having to hit an API I have no access to fixing and I need to start a timer showing how long someone has been in a queue for. The date I get back is in this format 1556214336.316. The problem is the year always shows up as 1970, but the time is the correct start time. I need to calculate the difference between the time now, and the time the conversation was created at. I have tried this with little success and was wondering if there is an elegant way to only get the difference in time and not the total amount of seconds.
convertDateToTimerFormat = (time) => {
const now = new Date();
const diff = Math.round((now - parseInt(time.toString().replace('.', ''))) / 1000);
const hours = new Date(diff).getHours();
const minutes = new Date(diff).getMinutes();
const seconds = new Date(diff).getSeconds();
return `${hours}:${minutes}:${seconds}`;
}
The weird parseInt(time.toString().replace('.', ''))) seems to fix the 1970 issue, but I still can't get the data to be manipulated how I need.
I tried the momentjs library, but their diff method only appears to allow for days and hours.
Any help/guidance, would be much appreciated.
Edit with working code:
convertDateToTimerFormat = (time) => {
const now = new Date();
// eslint-disable-next-line radix
const diff = new Date(Number(now - parseInt(time.toString().replace(/\./g, ''))));
const hours = diff.getHours();
const minutes = diff.getMinutes();
const seconds = diff.getSeconds();
return `${hours}:${minutes}:${seconds}`;
}
Unix time values are the number of seconds since the Epoch and won't have a decimal like your 1556214336.316
If I take 1556214336 (without the .316) and put it in a converter I get the output 04/25/2019 # 5:45pm (UTC) which is not 1970 — it seems an accurate time (I haven't independently verified)
It seems, then, your 1556214336.316 is the seconds.milliseconds since the epoch.
Javascript uses the same epoch, but is the number of milliseconds since the epoch, not seconds, so if I'm correct about the time you're getting you should be able to just remove the decimal place and use the resulting number string. Indeed
var d = new Date(1556214336316);
console.log('Date is: ' + d.toUTCString());
produces
Date is: Thu, 25 Apr 2019 17:45:36 GMT
which exactly matches the converter's time of "5:45pm"
var d = new Date(1556214336316);
console.log('Date is: ' + d.toUTCString());
Assuming your value 1556214336.316 is a String coming back from a web API, you can remove the decimal and your conversion can be done like this (note you don't have to keep creating new Date objects):
convertDateToTimerFormat = (time) => {
const d = new Date( Number(time.replace(/\./g, '')) );
return `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
};
console.log( 'time: ' + convertDateToTimerFormat('1556214336.316') );
Depending on your use, you may want to use getUTCHours() etc. instead.
I don't know about elegant, but this calculates and displays the expired time in h:mm:ss format:
console.log(convertDateToTimerFormat(1556215236.316));
function convertDateToTimerFormat(time){
// Converts `time` to milliseconds to make a JS Date object, then back to seconds
const expiredSeconds = Math.floor(new Date()/1000) - Math.floor(new Date(time * 1000)/1000);
// Calculates component values
const hours = Math.floor(expiredSeconds / 3600), //3600 seconds in an hour
minutes = Math.floor(expiredSeconds % 3600 / 60),
seconds = expiredSeconds % 3600 % 60;
// Adds initial zeroes if needed
if (minutes < 10) { minutes = "0" + minutes; }
if (seconds < 10) { seconds = "0" + seconds; }
// Returns a formatted string
return `${hours}:${minutes}:${seconds}`;
}
function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getUTCHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if (cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if (cur_mins < 10) {
cur_mins = '0' + cur_mins;
Here’s the code for a simple 24 hour countdown timer that resets again after each 24 hours but when I add, say, 11- hours in the compute time remaining section it occasionally throws a negative time (in hours) at me depending on the current UTC time. I’d just like the 24 hour period to start from a different time /time zone. All help greatly appreciated
You might be looking at this backwards :-) Why don't you create a Date object for midnight, then subtract current time from it. This example works for the local timezone, but you could easily adapt it for UTC, or another timezone.
// We're going to use Vue to update the page each time our counter changes.
// You could also do this old style, updating the DOM directly.
// vueStore is just a global variable that will contain the current time,
// and the function to periodically update it.
var vueStore = {
now: new Date(),
countdown(){
vueStore.now = new Date();
window.setTimeout(() => {this.countdown(); }, 1000);
}
};
vueStore.countdown();
var vm = new Vue({
el: "#vueRoot",
data: { vueStore: vueStore },
computed: {
timeTilMidnight() {
var midnightTonight = new Date(this.vueStore.now.getYear(), this.vueStore.now.getMonth(), this.vueStore.now.getDay() + 1);
var timeToMidnight = midnightTonight.getTime() - this.vueStore.now.getTime();
return new Date(timeToMidnight).toLocaleTimeString([], {
timeZone: "UTC"
});
}
}
});
<script src="https://unpkg.com/vue#2.5.17/dist/vue.js"></script>
<div id="vueRoot">
<h1>{{timeTilMidnight}}</h1>
</div>
My apologies if a similar question has been asked before - I could not find it on SO.
I've constructed a countdown clock in pure JS that will countdown opening times (different for Fri,Sat,Sund and the remaining weekdays). I have also offset the AEST timezone so that the time is constant no matter what internet connected device you are accessing in whatever timezone.
Works great! Although I'm working to streamline the code of course. Small bug I noticed this morning is that it likes to count down from 60secs and 60min instead of having them converted to the next unit of time up. (i.e. when the countdown started this morning at 10am to count down until 5pm, it began with 6 hours, 60 mins - definitely should be 7 hours!).
Anwyay, this is my code:
function ShowTime() {
//access system clock and get the time
var aest = new Date();
var localTime = aest.getTime();
//obtain local UTC offset and convert to msec
var localOffset = aest.getTimezoneOffset()*60000;
//Get total UTC time in msec
var utc = localTime + localOffset;
//obtain and add destination UTC time offset (Brisbane, Australia +10)
var offset = 10;
var brisbane = utc + (3600000*offset);
var brisDay = new Date(brisbane);
brisDay = brisDay.getDay();
//Set weekend days with different opening hours
//Set numbers representing weekend days - 0 for Sunday, 6 for Saturday
if (brisDay===0 || brisDay===5 || brisDay===6) {
var hoursBase = 16
var hoursBefore = 6;
}
else {
var hoursBase = 19;
var hoursBefore = 9;
}
//convert msec value (with timezone offset) to datetime string variables
var consTime = new Date(brisbane);
var brisHours = hoursBase-consTime.getHours();
var brisMinutes = 60-consTime.getMinutes();
var brisSec = 60-consTime.getSeconds();
//complete string for offset AEST local time
//show CLOSED message if past closing time
if (brisHours<0 || brisHours>hoursBefore) {
var timeLeft = "<strong style='background-image:url()'>The SLQ building is currently closed.</strong>";
} else if (brisHours<1 || brisHours>hoursBefore) {
var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
} else if (brisHours<2 || brisHours>hoursBefore) {
var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
} else if (brisHours<3 || brisHours>hoursBefore) {
var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
}
else {
var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
}
//output adjusted time into page
document.getElementById("countdown").innerHTML = timeLeft;
}
//Setup variable to update on setInterval function every 1000 milliseconds
var countdown = setInterval(ShowTime ,1000);
and here is a working JS Fiddle: https://jsfiddle.net/coolwebs/pbno1jhe/1/
I have looked into the problem and it appears as though my issue lies in the fact that I have set the
var brisMinutes = 60-consTime.getMinutes();
var brisSec = 60-consTime.getSeconds();
When I change these numeric values to be "59" - like I have in the provided JS Fiddle - it seems to resolve the issue but also appears to be slightly out of sync with the computer clock.
I think I have approached it incorrectly, so could someone please give me their opinion on the matter?
What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.
In JavaScript? Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time.
Nowadays you can get correct timezone of a user having just one line of code:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
You can then use moment-timezone to parse timezone like:
const currentTime = moment().tz(timezone).format();
Try
let s= new Date().toLocaleString();
console.log(s);
If you want to know the timezone of the client relative to GMT/UTC here you go:
var d = new Date();
var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, i.e. -0700
If you'd like the actual name of the timezone you can try this:
var d = new Date();
var tz = d.toString().split("GMT")[1]; // timezone, i.e. -0700 (Pacific Daylight Time)
UPDATE 1
Per the first comment by you can also use d.getTimezoneOffset() to get the offset in minutes from UTC. Couple of gotchas with it though.
The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for more documentation.
It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time.
UPDATE 2
While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).
If you want to know the timezone of the client relative to GMT/UTC here you go:
var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d)
var d = new Date().toString();
var tz = gmtRe.exec(d)[1]; // timezone, i.e. -0700
If you'd like the actual name of the timezone try this:
var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")"
var d = new Date().toString();
var tz = tzRe.exec(d)[1]; // timezone, i.e. "Pacific Daylight Time"
In order to get local time in pure Javascript
use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
directly like this :
new Date((new Date().setHours(new Date().getHours() - (new Date().getTimezoneOffset() / 60)))).toISOString()
more details in this utility function
function getLocaLTime() {
// new Date().getTimezoneOffset() : getTimezoneOffset in minutes
//for GMT + 1 it is (-60)
//for GMT + 2 it is (-120)
//..
let time_zone_offset_in_hours = new Date().getTimezoneOffset() / 60;
//get current datetime hour
let current_hour = new Date().getHours();
//adjust current date hour
let local_datetime_in_milliseconds = new Date().setHours(current_hour - time_zone_offset_in_hours);
//format date in milliseconds to ISO String
let local_datetime = new Date(local_datetime_in_milliseconds).toISOString();
return local_datetime;
}
Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.
I first wrote a php function to return the required dates/times to my HTML template
/**
* Gets the current location time based on timezone
* #return string
*/
function get_the_local_time($timezone) {
//$timezone ='Europe/London';
$date = new DateTime('now', new DateTimeZone($timezone));
return array(
'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
'local-time' => $date->format('h:i a')
);
}
This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.
<span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
<?php echo $time['local-time']; ?>
</span>
I then used the getUTCHours on my date object to return the time irrespective of the users timezone
The getUTCHours() method returns the hour (from 0 to 23) of the
specified date and time, according to universal time.
var initClocks = function() {
var $clocks = $('.box--location__time');
function formatTime(hours, minutes) {
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return {
hours: hours,
minutes: minutes
}
}
function displayTime(time, $clockDiv) {
var currentTime = new Date(time);
var hours = currentTime.getUTCHours();
var minutes = currentTime.getUTCMinutes();
var seconds = currentTime.getUTCSeconds();
var initSeconds = seconds;
var displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
setInterval(function() {
if (initSeconds > 60) {
initSeconds = 1;
} else {
initSeconds++;
}
currentTime.setSeconds(initSeconds);
hours = currentTime.getUTCHours();
minutes = currentTime.getUTCMinutes();
seconds = currentTime.getUTCSeconds();
displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
}, 1000);
}
$clocks.each(function() {
displayTime($(this).data('time'), $(this));
});
};
I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '×tamp=' + timestamp + '&key=' + apikey
var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
if (xhr.status === 200) { // if Ajax request successful
var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
console.log(output.status) // log API return status for debugging purposes
if (output.status == 'OK') { // if API reports everything was returned successfully
var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
console.log(localdate.toLocaleString()) // Display current Tokyo date and time
}
} else {
alert('Request failed. Returned status of ' + xhr.status)
}
}
xhr.send() // send request
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
I found this function is very useful during all of my projects. you can also use it.
getStartTime(){
let date = new Date();
var tz = date.toString().split("GMT")[1].split(" (")[0];
tz = tz.substring(1,5);
let hOffset = parseInt(tz[0]+tz[1]);
let mOffset = parseInt(tz[2]+tz[3]);
let offset = date.getTimezoneOffset() * 60 * 1000;
let localTime = date.getTime();
let utcTime = localTime + offset;
let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
let customDate = new Date(austratia_brisbane);
let data = {
day: customDate.getDate(),
month: customDate.getMonth() + 1,
year: customDate.getFullYear(),
hour: customDate.getHours(),
min: customDate.getMinutes(),
second: customDate.getSeconds(),
raw: customDate,
stringDate: customDate.toString()
}
return data;
}
this will give you the time depending on your time zone.
Thanks.
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
I needed to report to the server the local time something happened on the client. (In this specific business case UTC provides no value). I needed to use toIsoString() to have the format compatible with .Net MVC but toIsoString() this always converts it to UTC time (which was being sent to the server).
Inspired by the 'amit saini' answer I now use this
function toIsoStringInLocalTime(date) {
return new Date((date.getTime() + (-date.getTimezoneOffset() * 60000))).toISOString()
}
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT
just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()
my code is
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
<body onload=display_ct();>
<span id='ct' ></span>
</body>
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")