So what I need to try an accomplish is to output a specific message depending on how close a date is. The task is to change an element of a webpage from a message saying "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 months away, and finally "Renewal Required!" when the date is 1 month away.
So far I have:
if()
{<hre>Renewal Required!</hre>}
else if()
{<ha>Renewal upcoming</ha>}
else
{<hg>Renewal Unnecessary</hg>}
I am uncertain of how to write the condition for what i need the script to do, for example the renewal month or date might be the 26th February, and is there some way of making it work off the computers date.
Date.now returns currrent date in miliseconds. Just check for
renewal_date - Date.now()
And compare it with the corrent number of miliseconds.
Here's one way you could do it. You could expand this to be considerate of what day of the month it is, also. Live demo (click).
var deadline = new Date(2014, 1, 2); //2014, February 2nd (January is Month 0)
var today = new Date();
var monthDiff = deadline.getMonth() - today.getMonth();
if (monthDiff < 3) {
console.log('Deadline is in 3 months or less!');
}
if (monthDiff <= 1) {
console.log('Deadline is in 1 month or less!');
}
Answering your comment: There a are lots of ways this can be done - learn the basics. Here are two examples that might help.
var p = document.createElement('p);
p.textContent = 'My message here';
document.body.appendChild(p);
Or if the element already exists on the page:
var elem = document.getElementById('myElem');
elem.textContent = 'My message here';
Related
So, I need to calculate age by subtracting "todays" date from the converted date of an input field, entered by the user. Although it needs cleaned up, the below code works, I had to get creative as RN uses a different JS execution environment... see here.
My question, without adding the "+1" to this snippet "b.getMonth() + 1", the math on the date subtraction comes back 1 month off every time. When I add the "+1" it works like a charm, why? If it's a logical fix, I don't mind keeping the "+1," but I would surely like to know why the "+1" is necessary.
Also, totally open to improved solutions to this problem, keep in mind I had a much simpler function that worked great while debugger was open, once closed, it did not work, see the link above.
getVerifyBirthday(birthday) {
const b = new Date();
var verify = birthday.length;
const utc2 = Date.UTC(b.getFullYear(), b.getMonth() + 1, b.getDate());
if (verify === 10) {
const splitBirth = birthday.split('-');
var mydate = new Date(splitBirth[2], splitBirth[0], splitBirth[1]);
const a = mydate;
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const diffTime = Math.abs(utc2 - utc1);
const diffYears = (diffTime / (3.15576e+10));
this.setState({ diffYears: diffYears});
return diffYears >= 13;
} else {}
}
Update
I ended up refactoring my original function, leaving the (+1) on months due to months starting at 0, as mentioned below. I still had to split both dates, when I didn't split both, my age came back NaN/Undefined; not sure if this goes back to the RN execution environment vs browser, but I digress.
I'd make a few of my own suggestions over here:
there's no need to hussle with UTC dates (to make sure whether the user in his timezone has already reached the age of 13, assuming along the way that he or she was born in that same timezone ;)
there's no need to split mm-dd-yyyy date string to convert into Date, it may be parsed by new Date()
counting years as 365.25 days has certain error margin depending on the exact leap years quantity that passed since the user's birth year, instead whole years may be compared together with dates
To me, it makes more sense to decompose date strings into days, months and years and make decision based on full years difference minus 1 year (if the person didn't yet celebrate his/her birthday this year):
const today = new Date().toISOString().slice(0,10), // yyyy-mm-dd
birthday = '1982-06-21',
[bYear, bMonth, bDay] = birthday.split('-'),
[tYear, tMonth, tDay] = today.split('-'),
diffYears = tYear - bYear - (bMonth > tMonth || bDay > tDay ? 1 : 0)
console.log(diffYears)
.as-console-wrapper{min-height:100%;}
Months are zero-based in JavaScript Date objects. However, if you get a formatted string, they start from 1:
const date = new Date(2020, 1, 17); // 17th of February 2020
console.log("getMonth:", date.getMonth()); //month is 1
console.log("formatted:", date.toISOString()); //month is 2
So, actually what happens is that you're shifting both dates a month forward. This sort of works:
const originDate = new Date(2020, 1, 17); // 17th of February 2020
const originString = "2020-02-17".split("-");
const dateFromDate = new Date(originDate.getFullYear(), originDate.getMonth() + 1, originDate.getDate())
const dateFromString = new Date(originString[0], originString[1], originString[2])
console.log("dateFromDate:", dateFromDate); //month is 3
console.log("dateFromString:", dateFromString); //month is 3
When you do the subtraction it evens out but you can still run into an overflow of the date for months with different number of days:
const originDate = new Date(2020, 0, 31); // 31st of January 2020
const dateFromDate = new Date(originDate.getFullYear(), originDate.getMonth() + 1, originDate.getDate())
console.log("dateFromDate:", dateFromDate); // 1st of March 2020
This still works logically for most cases, however you are bound to run into a problem at some point if you shift months forward. So, instead you should be doing the opposite and subtracting 1 when converting a 1-based number into a Date object:
const originString = "2020-02-17".split("-");
const dateFromString = new Date(originString[0], originString[1] - 1, originString[2])
console.log("dateFromString:", dateFromString); //month is 2
I'd like to check the date if it's next month from the current.
Some test cases here
2020.1.1 2019.12.30 // true
2019.11.30 2019.10.10 // true
2019.12.11 2019.12.1 // false
So as you can see, I'd like to check if the date is next month from now.
Hope to get the brilliant idea!
Best
Kinji
You could try this approach, we have to handle the case when the dates are in the same year and also for December and January of the next year.
A simple algorithm can be created, whereby we multiply the year by 12, add the month and get the difference of this score between the two dates. As long as the value of this is 1 or -1 we have months that are adjacent. I'm presuming you only need to check if the first parameter is the next month to the second parameter, so we check for a difference of 1.
function isNextMonth(timeStamp1, timeStamp2, format = "YYYY.MM.DD") {
let dt1 = moment(timeStamp1, format);
let dt2 = moment(timeStamp2, format);
return ((dt1.year()*12 + dt1.month() - dt2.year()*12 - dt2.month()) === 1);
}
let inputs = [['2020.1.1','2019.12.30'],['2019.11.30', '2019.10.10'], ['2019.12.11','2019.12.1'], ['2020.12.1','2021.1.1'], ['2020.6.1','2020.5.1'], ['2021.1.1','2019.12.1'], ['2019.3.1', '2019.4.1']];
for(let [inputa, inputb] of inputs) {
console.log(`isNextMonth(${inputa}, ${inputb}): ${isNextMonth(inputa, inputb)}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
A very simple solution would be to use Moment’s isSame. This only checks the month. If you also want to make sure that the year matches you would have to make sure that nextMonth.getYear() matches dateToCheck.getYear()
var dateToCheck = new Date(2019, 11, 30)
var nextMonth = new Date()
nextMonth.setMonth(dateToCheck.getMonth() + 1)
moment(dateToCheck).isSame(nextMonth, 'month');
I am trying to figure out how to calculate future date compared to current date. For Example: (think of Deadline as a Date field)
- If Deadline (value form) is in the future but <= 12/31 of the current year, “This Year”
- If Deadline (value form) is in the future but > 12/31 of the current year, “Future”
So far, I am unable to figure this out within my code.
I need help with var theFuture AND to create a var for "is future but <= 21/31 of current year.
var theFuture = new Date("January 01 2020");
//theFuture.setDate(today.getDate());
//Compare the two numbers
if (dateToCheck < rightNow || dateToCheck == rightNow) {
theTiming = "Overdue";
g_form.setValue('u_timing', theTiming);
}
else if (dateToCheck >= approaching) {
theTiming = "Deadline Approaching";
g_form.setValue('u_timing', theTiming);
}
else if (dateToCheck > theFuture){
theTiming = "Future";
g_form.setValue('u_timing, theTiming');
}
}
So, results should be: When the user selects a date from Deadline, another field called Timing will generate Text. Current, I am able to calculate if the date selected is today or before today, Timing will say "Overdue". Next, if the date selected is greater than today BUT within 180 days, Timing will say "Deadline Approaching". But, to get the rest that I mentioned above, I am stuck.
We use moment.js for working with dates it makes things a lot easier.
This will tell you if the date selected is today or not:
var iscurrentDate = moment().isSame(dateToCheck, "day");
if(iscurrentDate)
{
}
You can also do a similar thing for year
var iscurrentDate = moment().isSame(dateToCheck, "year");
if(iscurrentDate)
{
}
More info on moment here: https://momentjs.com/docs/
I'm trying to get the start of (12:00am, or, 00:00am) of the most recent Friday. This has been working:
moment().isoWeekday(5).startOf('day').toDate()
But it only works Friday->Sunday, on Monday morning it will then refer to the upcoming Friday, in which case this would work:
moment().add('-1', 'week').day(5).startOf('day').toDate()
but I need it be dynamic and done in one line if possible, to where I don't to perform any checks on the current day.
Is there a way to always get the most recent Friday? Regardless of what the current day is.
Edit I'm also trying to get this to return the current day (friday) if executed on a Friday.
If you don't want to use a library, it's pretty straight forward
var date = new Date();
while ( date.getDay() !== 5 ) date.setDate(date.getDate() -1);
console.log(date)
With moment
var date = moment();
var friday = date.day(date.day() >= 5 ? 5 :-2);
and if millisecond accuracy doesn't matter, you could call moment() twice to make it one line (but I would much raher use a variable)
var friday = moment().day(moment().day() >= 5 ? 5 :-2);
Check this:
var date = moment().utc().isoWeekday(5);
if(moment().day() < 5) {
date = date.add(-1, 'week');
}
console.log('Recent friday starts:', date.startOf('day').toDate());
console.log('Recent friday ends:', date.endOf('day').toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"></script>
I am new to JavaScript but need to run a check to make sure it is daylight. I am using yahoo's weather API to pull sunrise and sunset. I'm just a little confused as to the best approach for comparing its results to the current time.
I am confused because it returns a time like sunset: '9:01 pm'. bsince there is a PM it is text. I can't think of a good way to compare it to the current time... RegExp, then convert to an integer maybe?
What would be the best approach to this, and why (sorry I'm trying to learn)?
Thanks in advance for any help.
Create a new Date() with the info from yahoo's api, then compare Date.now() with sunsetDate.getTime() and sunriseDate.getTime().
Passing today's date in mm/dd/yyyy format with the time as '9:01 pm' to the Date constructor will give you a valid date.
var today = new Date();
today = [today.getMonth()+1, today.getDate(), today.getFullYear()].join('/');
var yahooSunrise = '5:45 am';
var yahooSunset = '9:01 pm';
var sunrise = new Date(today + ' ' + yahooSunrise).getTime();
var sunset = new Date(today + ' ' + yahooSunset).getTime();
var now = Date.now();
var isDaylight = (now > sunrise && now < sunset);
This would work with something like this, but maybe you might need to change the timings to suite a particular climate:
function getNow() {
var now = new Date
if (now.getHours() < 5) { return "Could be still dark";}
else if (now.getHours() < 9) {return "Definitely day time";}
else if (now.getHours() < 17) { return "Definitely day time"; }
else {return "It gets dark now";}
}
alert(getNow());
One quick approach is to turn both the current time of day and the time you get back from yahoo into the value "minutes since the beginning of the day."
For example, if Yahoo gives you 9:01pm, use the pm to turn the time into 21:01. That is
21*60 + 1 = 1260 + 1 = 1261 minutes since the beginning of the day
Do this for both sunrise and suset. Then get the current time with
new Date()
and do the same kind of thing.
Then just do integer comparisons!
Hope that helps.
This sounds like a good candiidate for a regular expression on the data you get back from the service.
Something like (\d{1,2}):(\d{2})\s(AM|PM) will give you 3 capture groups.
1: The hour (1 or 2 digits)
2: The Minute (2 digits)
3: Either string "AM" or "PM"
You can then use these to parse out the actual time as integer hour and minute to compare to the current time.