Trying to add a timer to my website to countdown days - javascript

I'm trying to get a timer to count down to a date by days and I don't know why this isn't working it just says NaN
function daysUntil24thApril2016() {
var april2016 = new Date(24, 4, 2016);
var difference = april2016.getMilliseconds - Date.now().getMilliseconds;
return difference / 1000 / 60 / 60 / 24;
}
$(document).ready(function() {
console.log("asdasd")
$('#dateTime').text(daysUntil24thApril2016());
});

There are several mistakes you made in your script, I'll try to explain each to help you understand it and finally give you a corrected script the way you wrote it:
new Date() wants the year first, then month - 1 and finally the days. So to get the 24.04.2016, you have to do new Date(2016, 3, 24)
For a Date there is a getMilliseconds function, but it returns the milliseconds part of that date, not the unix timestamp you wanted
.getTime() is the function to get the unix timestamp in milliseconds from this date
Date.now() already returns the unix timestamp (a number), there is no getMilliseconds() for that and therefore it returned undefined
Even if there were a getMilliseconds function, the way you wrote it without the braces () would not have called it anyway but returned the function. They way you wrote it resulted in var difference = function - undefined which is NaN: "Not a number".
Therefore difference was no number in your example (it was Nan) and you cannot do any math with it obviously, it stays NaN
Using Math.floor will give you full days
See below for a version of your script where the points above are corrected.
function daysUntil24thApril2016() {
var april2016 = new Date(2016, 3, 24);
var difference = april2016.getTime() - Date.now();
return Math.floor(difference / 1000 / 60 / 60 / 24);
}
$(document).ready(function() {
$('#dateTime').text(daysUntil24thApril2016());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dateTime"></div>

Something like this will solve your problem:
function daysUntil24thApril2016() {
var april2016 = new Date("2015-04-24");
var difference = Date.now()-april2016;
return Math.floor((difference) / (1000*60*60*24))
}
$(document).ready(function() {
console.log(daysUntil24thApril2016());
});
When you subtract one Date object from another you will get the time difference in milliseconds. Using Math.floor() will return a whole (integer) number of days.

Related

How do I calculate date to not allow dates smaller than the current day?

I am making a business rule in which the customer's checkin can never be less than the previous day. but I'm just finding the difference between the days, in which case the values ​​are the same for later days and previous days, for example:
Current day: 11/02/2021
Checkin: 10/02/2021
Result: 1 day
Current day: 11/02/2021
Checkin: 02/12/2021
Result: 1 day
function calcularData(dataAtual, checkIn) {
const dataatual = new Date(inverterData(dataAtual));
const checkin = new Date(inverterData(checkIn));
const timeDiff = Math.abs(checkin.getTime() - dataatual.getTime());
const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
return diffDays
}
function inverterData(date) {
const regex = '^([0-9]{2})([0-9]{2})([0-9]{4})';
const dataFormatada = date.match(regex);
return `${dataFormatada[2]}/${dataFormatada[1]}/${dataFormatada[3]}`;
}
console.log(calcularData('11022021','10012021'))
Checkin: 02/12/2021
Result: 1 day
Your issue is using Math.abs for the days difference, so negative values become positive.
When getting days difference with whole dates, Math.round should be used so that small differences caused by daylight saving changes are filtered out. ceil will fix cases where a day is shorter than 24 hrs, but not longer. round fixes both.
Also, your method of parsing could be very much more efficient. Much better to get the values from the timestamp and pass them directly to the Date constructor than create another string that is then parsed by the internal parser, e.g.
// Return difference in days
function calcularData(s1, s2) {
// Parse timestamp in ddmmyyyy format to Date
let parse = s => new Date(s.substr(4,4), s.substr(2,2) - 1, s.substr(0,2));
return Math.round((parse(s2) - parse(s1)) / 8.64e7);
}
console.log(calcularData('11022021','10012021')) // -32
console.log(calcularData('11022021','10022021')) // -1
console.log(calcularData('11022021','12022021')) // 1

How to convert a string to time in javascript

I'm trying to create a countdowntimer in Javascript. There are a lof of examples on the internet. I'm trying to adjust these to my own needs. I want a countdown timer that, when started, countsdown to the whole hour. For example, if I run the code at 13:15 it wil count down to 14:00.
The problem I have is getting the time to countdown to.
var cd = new Date("Jan 5, 2021 15:37:25").getTime();
In the above example you have a defined date. I'm trying to change this to a time to the first upcoming hour. Below is what I have:
var countdowndate = newDate("cd.getMonth, cd.getYear (cd.getHour + 1):00:00").getTime();
This isn't working. What am I doing wrong here? Any help is appreciated.
Here's a very expressive way of solving this:
Get the current time stamp, floored to the last full minute.
Get how many full minutes remain until the next hour, transform to milliseconds.
Sum up the results of 1 and 2.
function getBeginningOfNextHour() {
const msPerMinute = 60 * 1000;
const currentDate = new Date();
const currentDateTimestampRoundedToMinute = Math.floor(+currentDate / msPerMinute) * msPerMinute;
const msUntilNextHour = (60 - currentDate.getMinutes()) * msPerMinute;
return new Date(currentDateTimestampRoundedToMinute + msUntilNextHour);
}
console.log(getBeginningOfNextHour());

Javascript pass value of time difference in hours * minutes * seconds * 1000

I have this JS script:
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : (new Date()).getTime() + 24*60*60*1000
});
}
It provides +24 hours as 24*60*60*1000 so script starts count down from 24:00:00
I need to give this script my event date as valuable format Y.m.d H:i I.E. 2014.12.31 12:00, that it would calculate the time difference between now and add it to the code.
var difference = getTimeDifferenceFromNow('2014.12.31 12:00')
timestamp : (new Date()).getTime() + difference
Substract two Date instances, you will get the length between in millisecond.
function getTimeDifferenceFromNow(timeString) {
return new Date(timeString) - new Date();
}
getTimeDifferenceFromNow('2014.12.31 12:00') // 818501769, roughly 9 days and half in the future.
How could this work? When you substract two Date instances, their valueOf() method is called internally, which will convert them to timestamp. Then you are actually subsctracting two timestamps, finally get a number of millisecond.
EDIT
However, I was wondering why you did in that way? If you want the timestamp of a given date/time, why don't you just instantiate it and grab its timestamp?
new Date('2014.12.31 12:00').getTime() // 1419998400000
This was the final solution:
var eventdate = new Date("January 1, 2015 1:00:00").getTime();
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : eventdate
});
}

javascript getTime() to 10 digits only

I am using the following function to get the Time using javascript:
function timeMil(){
var date = new Date();
var timeMil = date.getTime();
return timeMil;
}
And the value I get is:
1352162391299
While in PHP, I use the time(); function to get Time and the value I get is
1352162391
How do I convert the value of javascript time to remove the last 3 digits and make it 10 digits only.
From 1352162391299 To 1352162391
So that the Javascript time is the same with the PHP time.
I think you just have to divide it by 1000 milliseconds and you'll get time in seconds
Math.floor(date.getTime()/1000)
If brevity is ok, then:
function secondsSinceEpoch() {
return new Date/1000 | 0;
}
Where:
new Date is equivalent to new Date()
| 0 truncates the decimal part of the result and is equivalent to Math.floor(new Date/1000) (see What does |0 do in javascript).
Using newer features, and allowing for a Date to be passed to the function, the code can be reduced to:
let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0;
But I prefer function declarations as I think they're clearer.
Try dividing it by 1000, and use parseInt method.
const t = parseInt(Date.now()/1000);
console.log(t);
function ts() {
return parseInt(Date.now()/1000);
}
You could divide by 1000 and use Math.floor() on JavaScript.

Need to create a html page for adding X days to D.O.B

I'm looking for a HTML code that adds a fixed number of days to an entered Date of Birth. Thanks a lot! Even a partial code is much appreciated!
Here is how I'd do it. The function daysFromDate returns a Date object you can use. Instead of passing the DOB as a string you can also update it to use a Date object.
/*
days is the number of days to add, and dob a string like "4/24/2011"
*/
function daysFromDate(days, dob) {
var dates = dob.split('/');
var daysToMilli = days * 60 * 60 * 24 * 1000;
var d = new Date(parseInt(dates[2]), parseInt(dates[0])-1, parseInt(dates[1]));
var newTime = d.getTime() + daysToMilli;
return new Date(newTime);
}
To get the date 20 days from now you call: daysFromDate(20, "4/24/2011");
VBScript has DateAdd() so it's pretty simple. If you prefer JavaScript, just Google "javascript dateAdd" -- there are a zillion solutions out there. Here's one:
http://www.solutionbot.com/2008/06/20/javascript-dateadd-function/

Categories

Resources