I will prompt the user to enter the years he lived then it should return the seconds he lived.
The code:
let use = prompt("Enter number of years u lived: ");
let u = parseInt(use)
let time = new Date()
let compute = time.getFullYear() - u
console.log(compute.getSeconds()+time.getFullYear());
But I get an error that says 'Uncaught TypeError: compute.getSeconds is not a function'
Assuming an approximation is fine (because you're not asking for a birth date anyway), it might be the easiest to just multiply the number by the number of seconds per year.
const seconds = years * 60 * 60 * 24 * 365;
This is not exact because it's not accounting for leap day and leap second rules.
You can just do it the naive way:- multiply the year by '31,536,000'. But this will lack accuracy.
You're assigning compute an integer value by using getFullYear(). That's why you're getting a TypeError.
To calculate the number of seconds lived you can do what Evert suggests in his answer.
Related
not sure how exactly to phrase this question, but I want to basically "loop around" a date, when it's more than a base date
What does that mean?
Let's say my start date is 7/7/2021
And let's say that the input date is one year later than 7/7/2021 [not sure exactly due to leap years [in other cases] etc, but] let's say that's 7/9/2022
since it's more than a year, I want to "loop back" to the original date, and add the remainder [if that makes sense], so in this case the result would be
7/9/2021
basically, it finds the remainder after taking into account the extra year, if that makes sense
another example, say my base date is the same, and my input is
7/10/2026 [without leap years for now]
then the output should give
7/10/2021
because it's more than a year etc...
obviously in these cases I can simply subtract the years and keep the dates, but I don't know how to calculate it for different months and different days, while taking into account DLS and leap years etc...
so far I was able to come up with this function for calculating the difference of days between two dates with timezone offsets, based on other answers from here on similar questions, but I don't know how to apply it to the above case [obviously I can simply check the amount of times of differences for, say, 365 days between each one, but that wouldn't take nito account leap years...]
var yoymaweemBayn = (w, e) => {
var d1 = new Date(w)
var d2 = new Date(e)
var day2 = (d2 - d1) / 1000 / 60 / 60 / 24
var ac = day2 - (d2.getTimezoneOffset() - d1.getTimezoneOffset()) / (60 * 24)
return ac
}
k.onclick = () => {
ok.innerHTML = yoymaweemBayn(
d2.value,
d3.value
)
}
B"H
<br>
<input id=d2 value="7/7/2021">
<input id=d3 value="4/6/2023"><br>
<button id="k">Calculate?!</button>
<div id=ok></div>
To clarify:
How do I subtract a certain number of years from the latter date, until the date "loops back around" to be within the base year, while taking into account leap years [such that its not always 365 days apart]?
age=42;
days +=(age/4);//leap years
var days= age*365;
var hours= days*24;
var age;
console.log(hours);
This code was provided to me by mimo in one of the lessons but I'm not able to resolve this problem. Can you please help me resolve this inconvenience?
I, too, had a difficult time with this one. However, it was also my fault that I jumped into Making a Website project without learning Javascript first.
The answer to this is:
var age;
age = 42;
var days = age * 365;
days += (age / 4); *// Leap years
var hours = days * 24;
console.log(hours);
You can take leap years into account by multiplying by 365.25.
Check out this code snippet:
function ageInHours(years) {
return years * 365.25 * 24;
}
console.log(ageInHours(42));
The core issue is that you have to know which years it actually was.
Each 4 years there is leap year. You have number 42, which we can write as 10*4 + 2, because the number of 4 years period is our interest. To generalize it, its basically x*4 + 2 and the simples example to imagine how it works is when x=1.
So your example is almost the same as for 6 year period. And we can easily find two examples with different hour rate, based on leap year.
2010 - 2016 will have two leap years (2010 and 2014).
2007 - 2013 will have only one leap year (2010)
So in order to find correct number, you have to get start year and you have to cycle trough next 42 years. Whenever the year is multiplicable by 4, you add 1 extra day. But be aware, in case of 100 years (i.e. twenty years ago we had 2000), this rule is not used and its same as other years.
If I don't get you wrong and you only want to calculate year hours (and there are no specific boundaries for the years like 2000-2042), you can do as follows for any random year.
Since each year got 365 days and each day got 24 hours, You can simply calculate each year hours like this: year * 365 * 24. But in order to calculate leap years also, since leap years happen every 4 years, you should divide your desired year by 4 (In order to check how much leap years exist within it) and calculate the floor of it, then the floored number would be the extra days you got, so you should calculate them individually and sum it up with the specified year. So the final output should be something like this year * 365 * 24 + additionalDaysDueToLeapYears * 24.
Your code finally should be something like this:
function yearToHour(year) {
const leapYears = Math.floor(year / 4);
return year * 365 * 24 + leapYears * 24;
}
console.log(yearToHour(42));
42 * 8766 = 368172
done.
no javascript needed.
Can't seem to find information about how to round up the result of my hours results. Looking only limiting the output to 2 decimals.
For example, the console.log below will provide me with 1.4166666666666667 but I would like if it would round up to 1.47 (maximum of 2 decimals).
var startTime = $('2016-02-21 18:00');
var endTime = $('2016-02-21 19:25');
var duration = moment.duration(moment(endTime, 'YYYY/MM/DD HH:mm').diff(moment(startTime, 'YYYY/MM/DD HH:mm')));
var hours = duration.asHours()
console.log(hours);
Would anyone know if this is possible using moment JS? I created an example of this script here https://jsfiddle.net/ewmq6sof/1/ if that would help.
The easiest thing to do is to just use .toFixed(2)
var hours = duration.asHours().toFixed(2)
If you always want to decimals, or use Math.round()
var hours = Math.round(duration.asHours() * 100) / 100
if you want a maximum of two decimals.
No need for moment here.
How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/
I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?
is this the correct way to calculate any given date?
Regards
What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.
Although your date_to_reply is already in the past, theres still a 5 day difference.
So, everythings fine - it's the correct way.
EDIT:
If you want a negative value as result, try this:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().
If you want the value to be negative (indicating date_to_reply is in the past) you should subtract the past date from the current: date_to_reply.getTime() - today.getTime().
Check this link for ways to calculate more diffentiated results.
If you swap the order of the dates, you'll get the negative number you want.
Better yet you could write a function that does this.
It could subtract the first parameter from the second.
The second parameter could default to today.
function diffDates(dateOne, dateTwo) {
if (typeof dateTwo === 'undefined') {
dateTwo = new Date();
}
return dateOne.getTime() - dateTwo.getTime();
}
It would be better to have the function operate on numbers rather than dates.
That would be more flexible, but I'm typing on an iPad right now!
Its obvious because today's date is greater than the previous. So either you need to make it negative on your own or use this
var timeinmilisec = date_to_reply.getTime()-today.getTime();