In Javascript whenever we call the getDate() method a value of 1-31 is returned for the particular day of the month. This creates a problem in my countdown timer when I specify a future date in var goal that is greater than 31 which causes the countdown timer to output '12' instead of the number of days that are actually left until the future date.
function twoDigits(number) {return (number < 10 ? '0' : '') + number};
var goal = "Sun January 01 2012 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = new Date(goal.getTime() - now.getTime());
var day = count.getDate() -1;
var hour = count.getHours()-1;
var format = twoDigits(day) + ":" + twoDigits(hour) + ":" + twoDigits(count.getMinutes()) + ":" + twoDigits(count.getSeconds());
$(function () {
$('#counter').countdown({
image: 'digits.png',
startTime: format
});
});
Any ideas how I could fix this?
function padLeft(str,len,char) {
len=Number(len)||1;
char=String(char)||" ";
for(var i=0;i<len;i++)str=char+str;
return str.substr(str.length-len);
}
//$(document).ready(function() {
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = goal.getTime() - now.getTime();
var sign = count/Math.abs(count);
count = Math.abs(count);
var days = Math.floor(count/(24*60*60*1000));
count -= days*24*60*60*1000;
var hours = Math.floor(count/(60*60*1000));
count -= hours*60*60*1000;
var minutes = Math.floor(count/(60*1000));
count -= minutes*60*1000;
var secs = Math.floor(count/1000);
var startTime = days +":"+ padLeft(hours,2,"0") +":"+ padLeft(minutes,2,"0") +":"+ padLeft(secs,2,"0");
alert(startTime);
/*
$("#counter").countdown({
image: 'digits.png',
startTime: startTime,
format: "dd:hh:mm:ss"
});
*/
//}
This is not an exact fix for your code's issue
but if you want helper methods for dates, take a look at sugar.js it has a host of helper methods, like easily calculating the difference in days between now and a given date.
look at the features page for all date methods
you could use this function for example:
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var difference = goal.daysFromNow();
daysFromNow() is already an alias for daysUntil() & daysSince() which are for calculating differences in the past or future, daysFromNow() takes care of the past and future at once :)
and that variable would give you the total amount of days, even if it's more than 31 days.
Related
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 have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?
I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.
Prefix it with a date:
var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the start of the day;
Or, if you need it to be today's date:
var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the epoch.
You can add the following function that does the job for you :
function getDateFromHours(time) {
time = time.split(':');
let now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));
To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.
Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.
let timeString = "01:12:33";
Extract values with RegEx
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
Convert HH, MM and SS to milliseconds
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
In relation to another point in time, a reference time has to be given.
For instance,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)
I have written the following code and cannot figure out why it is not working in my Google Sheet:
function WEEKOF(myDay, myDate) {
var wkDate = new Date(myDate);
var StartDate = new Date();
StartDate.setDate(wkDate.getDate()-myDay);
return StartDate;
}
=WEEKOF(Weekday(A1), A1)
Cell A1 contains: 05/01/2016
Return: 7/26/2017
I'm expecting the return to be: 04/29/2016
Difference in Days,Hours,Minutes and Seconds
var adayinmilliseconds=24*60*60*1000;
var differenceBetweenTwoDatesInDays = Math.floor((date1.valueOf()-date2.valueOf())/adayinmilliseconds);
A Date Difference Function that output days, hours, minute and seconds. From the MDN Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. The method of time() and valuOf() both provide us the the primitive value of dates ie the number of milliseconds from some date in the past. Yes, it can be quite a large number but in the end with a little simple arithmetic Math.floor(), /, % you end up with an easy calculation. You can change the output to an array or an object depending upon your requirements.
function calcTimeDifference(Start,End)
{
if(Start && End)
{
var second=1000;
var minute=60*second;
var hour=minute*60;
var day=hour*24;
var t1=new Date(Start).valueOf();
var t2=new Date(End).valueOf();
var d=t2-t1;
var days=Math.floor(d/day);
var hours=Math.floor(d%day/hour);
var minutes=Math.floor(d%day%hour/minute);
var seconds=Math.floor(d%day%hour%minute/second);
return 'dd:hh:mm:ss\n' + days + ':' + hours + ':' + minutes + ':' + seconds;
}
else
{
return 'Invalid Inputs';
}
}
I am using sharepoint 2013 online. I have created a custom list. On this list I have used JSLink to show an icon in a column. I would like to do some logic to show a red or a green icon. I have now in js 2 dates. The date from my column from the current item and the date of today. I would like to do the following check:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
if((contractEndDate + 10 days) > today)
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/green.png'/>";
}
else
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/red.png'/>";
}
How can I cast the var contractEndDate to a date? And how can I increase it with 10 days?
Add 10 and compare:
var endPlus10 = new Date(contractEndDate);
endPlus10.setDate(contractEndDate.getDate() + 10);
if (endPlus10 > today) ...
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC. You can compute the number of milliseconds in a day (see one_day variable) and compare dates.
See my JS Fiddle, http://jsfiddle.net/cVm59/1/
var contractEndDate = new Date("2-18-2014"),
today = new Date(),
one_day = 1000 * 60 * 60 * 24;
if((contractEndDate.getTime() + (one_day*10)) > today.getTime())
{
console.log("Less than 10 days ago");
}
else
{
console.log("More than 10 days ago");
}
This should be what you are looking for:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
var CED = new Date(contractEndDate);
CED.setDate(CED.getDate() + 10);
if(CED > today)
{
Create CED as a new date and then using the setDate this just adds 10 days before you make your comparison. You could clean this up and just set your contractEndDate as a new Date, but up to you.
I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7: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;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);