Doing math towards future date - javascript

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/

Related

Momentjs / Angularjs - Checking if 2 dates are in the same period - TimeSheet project

I am working on a simple Timesheet app, I am trying to implement an auto calculator that will sum up your hours for each day (Sunday, Monday, Tuesday, etc ...). A problem I noticed is that in some cases, users will enter activities that will be within the same date time periods.
For example:
$scope.Example = [
{Description:"Example activity",Start:"2018-06-24 8:00",End:"2018-06-24 10:00",Total:2},
{Description:"Example activity2",Start:"2018-06-24 9:00",End:"2018-06-24 10:00",Total:1},
{Description:"Example activity3",Start:"2018-06-24 10:00",End:"2018-06-24 11:00",Total:1}];
$scope.Calculate_all_entries = function(){
$scope.Total.Sunday = 0;
if($scope.Example){
angular.forEach($scope.Example, function(element){
if(moment(element.Start).format("dddd") === "Sunday"){
$scope.Total.Sunday = $scope.Total.Sunday + element.Total;
}
})
}
}
In this case the total should be 3 hours and not 4 hours as we dont charge for work within the same hours. I'm need to implement a system that would check if the dates are within the same period and provide the appropriate total.
I found this in the documentation on momentjs that seemed to be close to what i need but only takes one value:
moment('2010-10-19 11:00').isBetween('2010-10-19 10:00', '2010-10-25 00:00'); // true
Would anyone know of any other methods to check wether or not the start and end time are in the same period as other entries in the same day?
Sure, you can use momentjs's unix() function to convert those date times to an integer which then can easily be used to check whether the timestamp is in between two other timestamps.
Here is an example:
var timeToCheck = moment('2010-10-19 11:00').unix();
var startTime = moment('2010-10-19 10:00').unix();
var endTime = moment('2010-10-25 00:00').unix();
console.log(timeToCheck >= startTime && timeToCheck <= endTime); // true

JavaScript to check selected date is today's date and time is 2pm using Moment.js

How do I compare today's time and date with user selected date. If user selects today's date or tomorrow's date and time is 2pm or more than 2pm then I should show alert saying delivery time over.
I have tried something like this
$scope.checkDateTime=function(){
angular.forEach($scope.orders.start_date,function(s){
console.log(s);
var curTime = moment().format('YYYY-MM-DD HH:mm:ss');
var orderTime = s+' 14:00:00';
console.log(moment(orderTime).diff(curTime,'seconds'));
if(moment(orderTime).diff(curTime,'seconds')>86400) {
console.log('hooray!')
}
})
}
I have orders.start_date is a input field inside ng-repeat so I am using forEach loop. I just want to check if selected date is today's or tomorrow's date. Then I have to check time, and if it's greater than 2pm then I should not allow. Otherwise I can allow.
I am not sure when the acceptable order period starts (since checking if the day is today or tomorrow means that everything from 00:00 to 14:00 is a fair game) , but here is the is one way to do it based on your code:
$scope.checkDateTime = function(){
angular.forEach($scope.orders.start_date, function(s){
console.log(s);
var selectedTime = moment(s);
// create boundaries for time ranges
var today_end = moment("14:00","HH:mm"); // today 14:00
var today_start = moment().subtract(1,'day').endOf('day'); // end of yesterday (since we need to include 00:00 of today)
var tomorrow_end = moment("14:00","HH:mm").add(1,'day'); // tomorrow 14:00
var tomorrow_start = moment().endOf('day'); // end of today (since we need to include 00:00 of tomorrow)
// check if time in questions fits any of the ranges
if( ( selectedTime.isBetween(today_start, today_end) ||
( selectedTime.isBetween(tomorrow_start, tomorrow_end) )
console.log('hooray!')
}
})
}
Note, that isBetween(t1, t2) does not include t1 and t2 into the accepted range.

JS function...Write a function to find the weekday of the user's birthday

-Use window.prompt to generate a dialog box asking the user to type in his/her birthday.
-Write a function to find the weekday of the user's birthday.
-Respond to the user with a sentence telling the user the weekday (weekday name) of his/her birthday. Ex. "You were born on a Wednesday."
-The script should include necessary data validation. Respond to the user appropriately when the date provided by the user is not a valid date. (However, future dates are allowed.)
I have no Idea how to do this.. (hw assignment) I have this currently.... and all this is doing for me is telling me I was born on Feb. 12 which is a thursday. I'm not too sure where to start. What kind of function do I need to make for this to work???
var bday;
bday = window.prompt("When is your birthday?","");
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday', 'Saturday']
var currentTime = new Date();
var currentDay = currentTime.getDay();
var currentDayName= days[currentDay];
document.write("You were born on "+currentDayName);
Try something like this:
var bday;
bday = window.prompt("When is your birthday (YYYY-MM-DD)?","");
var bdayArray = bday.split('-');
//validation
if(bdayArray.length !== 3){
alert("invalid Date");
}else{
if(!bdayArray[0].match(/^\d\d\d\d$/) ||
!bdayArray[1].match(/^\d\d$/) ||
!bdayArray[2].match(/^\d\d$/)){
alert("invalid Date");
}else{
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday', 'Saturday'];
var currentTime = new Date(
parseInt(bdayArray[0]),
parseInt(bdayArray[1]) - 1, //month starts from 0
parseInt(bdayArray[2])
);
var currentDay = currentTime.getDay();
var currentDayName= days[currentDay];
document.write("You were born on "+currentDayName);
}
}
You could also use momentjs to make date operations more easy.
I won't write your homework for you, but this is generally what you want to do:
Get user's birthday
Create a new Date object with the date set to that birthday
Use the getDay method of the date object
Convert the number representing the day of the week to the actual string for that day.
You need a function to get user input and convert it to a Date object. You can make it manually, but you'll know that this function is already implemented in web browsers if you search more.
Take a look at this MDN document to see how you can make a Date object from a string. A document about Date.parse() may also help you.

How do I change something depending on date?

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';

Need explanation of this Date Processing function

Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
​function ​daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.

Categories

Resources