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]?
Related
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.
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.
I have a requirement where I want to calculate back date.
For example if I am giving 5 months then it should return the 5 month back date and if i give 5 years then it should return the 5 years back date keeping leap year in mind.i tried to implement some of the examples which I found in web but non of them are giving me the exact result.
Can someone please help me to achieve so.
You can use setMonth setDate and setFullYear on a Date object easily.
The thing is, if you're adding a whole year, and it's a leap year, you'll still end on the same date (month and day) of the last year. which i think it's the correct behaviour.
now = new Date() // 2016-11-24T13:21:55.841Z
now.setFullYear(now.getFullYear() -1) // 2015-11-24T13:21:55.841Z
If you want to subtract a standard-sized-year, I think you should instead remove 365 days from the current day. Which will take you to a slightly different date.
now = new Date() // 2016-11-24T13:21:55.841Z
now.setDate(now.getDate() - 365) // 2015-11-25T13:21:55.841Z
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 have an old web app where Javascript is used to validate some dates. Users usually use 2-digit years and I recently discovered it was evaluating 00 as 1900 instead of 2000
if (new Date(tb[0].value) > new Date(tb[1].value)){
alert('Starting date must come before the ending date');
tb[0].focus();
return false;
}
Entering 1/1/99 in the first box and 1/1/00 in the 2nd will cause an error message saying the start date has to be before the end date because 99 is evaluating at 1999 while 00 is evaluating at 1900.
Of course, Users can get around this using 4-digit years, but I still want to know what can be done to get Javascript to evaluate 2-digit years correctly.
So my question is, how can I get Javascript to evaluate 00 as 2000 and not 1900?
It does that because the language was created in the 1990's (and in a hurry). You can use getFullYear() and setFullYear() to handle years in a non-goofy way.
What I've done is write some code to check for year values less than 100, and if it's greater than 90 (or something similarly appropriate, depending on the situation) assume it's in the 20th century, otherwise assume the 21st.
And #Rachel no there's no way to tell the runtime library to behave differently, at least not any standardized way. That's just how the Date code works.
The simplest way is just to accept it does it that way and check for it.
if (date.getFullYear() < 1970) {
date.setFullYear(date.getFullYear() + 100);
}
1970 is of course just an example value as you have to have a sensible break point. You may want to do that as current year - x instead of a constant of course.
Chrome actually handles this correctly, but IE and Firefox (at least) do not. Here's my solution:
var x = new Date(input); //parse the date initially
if (x!="Invalid Date") {
var n = input.split(/[/-]/); //regex to look for / or - delimited dates
if (n[2].length == 2) //if the input has a 2 digit year
{
var y = x.getFullYear();
if (y < 1950) //and the parser decided it's before 1950
x.setFullYear(y + 100); //add a century
}
}
output = dateToShortString(x); //custom function to standardize formatting
The way I've done this in the past is to select an arbitrary year that lets the code assume that 2 digit years prior to that arbitrary year are in the 1900's, while years after that are in the 2000's. For an accounting app I had to make Y2K compliant, if I recall correctly, I chose 1940. So transactions between 40-99 were 1940-1999, and transactions 00-39 were 2000-2039.
is there a reason you couldn't do something along these lines?
The big assumption being that if the user is entering a 2 digit year that its probably not intended to be over 100 years in the past.
myDate('2-1-00');
function myDate(date) {
let today = new Date();
date = new Date(date.split('-').join('/'));
if ((today.getFullYear() - date.getFullYear()) >= 100) {
date.setFullYear(date.getFullYear() + 100);
}
alert(date);
}