I have a quiz program written in vanilla JS. It is supposed to log the time it takes to complete it.
What I would like to achieve is how long it takes for the user to answer the questions by subtraction two variables (strings). If it is even possible.
When the user has stated his name and presses a button "STart Quiz" the currrent time is logged in localstorage like so:
var storeName;
var d = new Date();
var h = getHours();
var m = getMinutes();
var s = getSeconds();
var startTime = h + ":" + m + ":" + s;
var endTime = h + ":" + m + ":" + s;
var result;
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
The tricky part is I do not know how to subtract startTime from EndTime to get the time it took to answer the questions. This quiz is over in minutes, so to use the hour is redundant.
When the user has clicked "submit" answer on the last question I want the time logged in LS as endTime.
I hope I have not been unclear and thank you all in advance very much for your time. Thank you.
Instead of storing string as date, directly store the time in milliseconds. Then you can subtract the start time with end time to figure out the time difference.
var startTime = Date.now();
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
Later you can calculate the endTime using Date.now() and subtract that from startTime to get the time difference.
storage.endTime = Date.now();
//difference
var diff = storage.endTime - storage.startTime;
You use your new Date() wrong.
Should be this.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
console.log(h);
As for futher implementation you should save current time then use timer on click/login. After that substract these two values. Example for seconds. You just devide (and/or take a modulo to go to real minutes at current time) by for example 3600 to get seconds instead of an hour. Or you can use all your variable and subtract the time. On the way if you get problems with addition for example you can get 5 + 3 = 53 instead of 8 you use Number(5) + Number(3) to do adition instead of concat. Good luck :P
EDIT: also to get time from your string. With split you get array of value.
var test = h + ":" + m + ":" + s;
console.log(test.split(":"));
Related
I have a variable that stores a time value.
var cabtime = ["09:30:00"];
Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.
I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.
Any pointers in this regard?
You could parse the time into seconds since midnight using:
var cabtime = ["HH:MM:SS"] // in 24hr time
function parseTime (string) {
parts = string.split(':').map(x => parseInt(x))
seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
return seconds
}
Then you can parse the time and the upper/lower bounds, and test using:
time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')
if (time >= lower && time <= upper) {
print('Inside the range')
}
You can solve it easily by converting your strings to Date objects and compare them than.
var cabtime = ["09:30"];
function checkTimeRange(time, from, to, reldate) {
if (undefined === reldate) {
reldate = '0000T'; // the date the time strings are related to
}
let dtime = new Date(reldate + time);
let dfrom = new Date(reldate + from);
let dto = new Date(reldate + to);
return dfrom <= dtime && dtime <= dto;
}
checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true
If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.
* update: changed the wrong date format to standard format
* update: changed the date format again to be more fancy
I need to get the duration between two dates in hh:mm:ss format using moment. but i am not able to get the exact difference. Here is my example.
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let diff = end.diff(start);
let f = moment.utc(diff).format("HH:mm:ss");
alert(f);
For the above dates i need to get the output as 24:00:00, because it's one day difference. But i am getting 00:00:00 as response.
If i am changing the hrs it should display based on that. how can i achieve this? can someone help me to fix this.
There's a rather lengthy discussion on Moments GitHub Page but this may be what you are after:
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let duration = moment.duration(end.diff(start));
let f = Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
alert(f);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
By the way there is a plugin that someone created for this specific issue, which is posted on Moments Website as well.
try this:
let f = moment.utc(diff).format('D[days] H[ hours]');
Example
If you want to convert that time in only HH:mm:ss maybe you can manually convert it to miliseconds and parse it to hours.
Try the following to achieve the quest.
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let diff = end.diff(start);
var d = moment.duration(diff, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
var secs = Math.floor(d.asSeconds()) - mins * 60 - hours * 60*60;;
console.log( hours + ":" + mins + ":" + secs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
It states
enter code here
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
Thus, stating your time as HH will give you 24h format, and hh will give 12h format.
Since the difference is a day so hours,minutes,seconds return zero so change the condition in this way
let f = moment.utc(diff).format("HH:mm:ss");
if(f=="00:00:00"){
f=moment.utc(diff).format("D[days] H[hours]");
}
What you are doing is trying to format a difference of 2 dates which will result in a date formated string, what you need to do is to get the difference in hours of both dates, to do that, you need the duration method:
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T13:56:33.763Z");
let diff = end.diff(start);
let diffData = moment.duration(diff);
alert((diffData.days() * 24) + diffData.hours());
This will help you.
var units = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var unitmapping = {month:12,day:30,hour:24,minute:60,second:60,millisecond:1000};
function getDiff(start, end)
{
var duration = "", start = moment(start), end = moment(end);
units.forEach(function(unit,index){
var diff = Math.abs(end.diff(start,unit));
if(unitmapping[unit]) diff = (diff%unitmapping[unit]).toFixed(0);
duration += diff + " "
+ unit
+ (diff==1 ? "":"s")
+ (index!=units.length-1 ? " : ":"");
});
return duration;
}
console.log(getDiff("2018-07-27T14:56:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-26T14:56:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-27T14:46:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-27T14:56:33.843Z","2048-07-29T14:56:33.763Z"));
console.log(getDiff("2018-09-27T14:56:33.843Z","2048-07-29T14:56:33.763Z"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format
07/26/2017
when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.
campMethods.EndDateAlert = function (dateString) {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var $EndDateSpan = $('.campaign-end-date');
if (dateString <= twoWeeks) {
$EndDateSpan.addClass('red');
}
return dateString;
};
You can do that with some Math. The key is, 2 weeks = 14 days.
Here is Pure Javascript example for you:
var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);
var currentDate = new Date();
var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2);
var compareDay = formatedDate - today;
if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}
Javascript Date Reference
Try comparing milliseconds of the dates.
We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.
let dueDate = new Date('07/26/2017');
if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
//do stuff
}
I'm trying to get the closest time in an array or list ect.
I was able to locate this code and have tried to get it to work by making edits but without any luck.
Can use jquery if it makes it easier. below is only javascript though
How can I output the time closest to the time which = thetime
After more research I have found this snippet and think it may be useful for my cause:
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
What I'm trying
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
var thetime = hours + ":" + minutes + " "
var json = [{
"times": {
"times1": "20:01",
"times2": "21:43",
"times3": "22:56",
"times4": "23:21"
}
}]
var times = [];
var jsontimes = json[0].times;
for (var i in jsontimes) {
times.push(new Date(jsontimes[i]))
}
times.sort(function (a, b) {
return Math.abs(thetime - a / new Date()) + Math.abs(thetime - b / new Date())
});
// display code
for (var i = 0; i < jsontimes.length; i++)
document.getElementById("output").innerHTML += dates[i] + "<br>";
You're trying to create Date objects with invalid values (e.g., "20:01"), resulting in invalid dates. According to MDN, you can pass parameters in the following ways when creating a new Date object:
Date(value)
Date(dateString)
Date(year, month, day [, hour, minute, second, millisecond])
where
value is an "integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)." and
dateString is a "string value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 2822 timestamps)."
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
This doesn't really answer your initial question, but it should help you create an array with the values you want.
So I am storing times as '01:30:00'. I have a start time and a date time dropdown. I want the dropdown to be set to the start time + 1hr. Is there a way to add the time via javascript or jquery?
Here's my current code:
$(".start_time").change(function(){
$(".end_time").val($(this).val());
});
Try this:
find the selected index of the start time
bump it up by 2 to find your end time index (given that you've got half hour increments)
use the mod operator % to wrap back to index 0 or 1 (for 00:00 and 00:30 respectively)
$(".start_time").change(function(){
var sel =$(this).attr('selectedIndex');
var endIdx = (sel + 2) % 48; // 47 is 23:30, so 48 should go back to index 0
$(".end_time").attr('selectedIndex', endIdx);
});
Try it out on JSBin.
There are two separate problems here: the first is parsing out the time from your .start_time input, and the second is incrementing it to be an hour later.
The first is really a string-manipulation exercise. Once you have parsed out the pieces of the string, e.g. via a regex, you could either turn them into a Date instance and use setHours, or you could just manipulate the components as numbers and them reassemble them into a string in the format you desire.
An example of this might be as follows:
var TIME_PARSING_REGEX = /([0-9]{2}):([0-9]{2}):([0-9]{2})/;
function padToTwoDigits(number) {
return (number < 10 ? "0" : "") + number;
}
$(".start_time").change(function () {
var stringTime = $(this).val();
var regexResults = TIME_PARSING_REGEX.exec(stringTime);
var hours = parseInt(regexResults[1], 10);
var newHours = (hours + 1) % 24;
var newHoursString = padToTwoDigits(newHours);
var minutesString = regexResults[2];
var secondsString = regexResults[3];
var newTimeString = newHoursString + ":" + minutesString + ":" + secondsString;
$(".end_time").val(newTimeString);
});
Basic example...
var date = new Date();
var h = date.getHours() + 1;
var m = date.getMinutes();
var s = date.getSeconds();
alert('One hour from now: ' + h + ':' + m + ':' + s);
Demo: http://jsfiddle.net/fBaDM/2/
After you parse you date/time string, you can use methods such as .setHours in your date object (more info at Mozilla Developer Center).
I highly recommend the DateJS library for working with date and time. I'm sure it'll be very handy for you.
protip: try to avoid replacing JavaScript with "jQuery markup"; it's all JS, after all. :)