Compare two dates in JS - javascript

I want to compare the user's birthday against today's date and get the number of days in between. The birthday they enter will be in the form of 12/02/1987 in an input box of type text
In my JS file I have code that looks like this:
function validateDOB(element) {
var valid = false;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //do that January is NOT represented by 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var today = mm + '/' + dd + '/' + yyyy;
alert(today);
if (element.value != today) {
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2011");
today = new Date();
difference = today - Christmas
days = Math.round(difference / (1000 * 60 * 60 * 24)-1);
alert(days);
valid = true;
}
Instead of using "Christmas" I want to compare element.value... how do I do this?
When I put difference = today - element.value it won't show me the difference. The alert box comes up as NaN.

I wrote a lightweight date library called Moment.js to handle stuff like this.
var birthday = moment('12/02/1987', 'MM-DD-YYYY');
var inputDate = moment(element.value, 'MM-DD-YYYY');
var diff = birthday.diff(inputDate, 'days');
http://momentjs.com/docs/#/displaying/difference/

You'll need to first parse element.value as a date:
difference = today - new Date(element.value);
http://jsfiddle.net/gilly3/3DKfy/

Related

How would I fix this function to change month depending on the date?

I'm trying to create a function that creates a dynamic date range based on the date supplied in a string.
What I've done so far:
Capture date in the string I'm looking to change;
Check to see if that date is a Thursday (if so the range will need to account for the weekend)
What I need to do:
Find a way to get the second date in the range to account for the weekend;
Find a way to make sure that the second date takes into account the last day of the month.
Apologies for old syntax, GTM doesn't like anything using ES6 so I'm a little constrained on this project.
Note I am using DD/MM/YYYY
var regex = /[\d\/\d\/\d]/g;
var text = document.querySelector('.shipmentLineTitle b');
var originalDate = text.innerText.match(regex, "");
if (originalDate.length > 10) {
originalDate.pop();
originalDate.join('');
}
var ogDateString = originalDate.join('');
var dayNumber = originalDate.splice(0, 2).join('');
var monthNumber = originalDate.splice(1, 2).join('');
var yearNumber = originalDate.splice(2, 4).join('');
// if originalDate is a thursday (5) dynamicString will need to be a Monday (1).
var date = new Date(yearNumber, monthNumber -1, dayNumber);
var dynamicDateString = "";
if (date.getDay == 5) {
var newDate = new Date(date) + (86400000 * 3);
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dymamicDateString = dd + '/' + mm + '/' + yy;
} else {
var newDate = new Date(date) + 86400000;
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dynamicDateString = dd + '/' + mm + '/' + yy;
}
var newContent = 'Delivery will be made between ' + ogDateString + ' - ' + dynamicDateString + '. An accurate delivery date will be provided after you place your order.';
text.innerText = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 09/10/2020 (1 delivery)</b></span>
Thursday is day 4
Here is a simpler script
var textField = document.querySelector('.shipmentLineTitle b'),
text = textField.innerText,
originalDate = text.match(/\d{2}\/\d{2}\/\d{4}/)[0].split("/"),
dayNumber = +originalDate[0],
monthNumber = +originalDate[1],
yearNumber = +originalDate[2],
date = new Date(yearNumber, monthNumber - 1, dayNumber, 15, 0, 0, 0),
aDay = 86400000,
newDate = new Date(date),
day = date.getDay(),
daysToAdd = 1; // Sunday to Wednesday
// if originalDate is a Thursday (4) or Saturday (6), dynamicString will need to be a Monday (1).
if (day === 4) daysToAdd = 4; // Thursday - delivery Monday
else if (day === 6) daysToAdd = 2; // Saturday
newDate.setDate(newDate.getDate() + daysToAdd);
var dd = newDate.getDate(),
mm = newDate.getMonth() + 1,
yy = newDate.getFullYear(),
dynamicDateString = dd + '/' + mm + '/' + yy,
newContent = text + ' - ' + dynamicDateString + '</b>. An accurate delivery date will be provided after you place your order.';
textField.innerHTML = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 08/10/2020 (1 delivery)</b></span>
I would suggest to user moment.js a very good date library to manipulate dates. It has lot of function to add/substract dates, hours, days etc.
There is https://www.npmjs.com/package/moment-business-days which servers exactly what you need

Calculate difference in days between a date pulled from an API and todays today

I am currently trying to figure out how to calculate the difference in days between a date pulled through from an API and today's date.
this is the code I have used to get todays date in the format that matches date from the API:
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
This twig code pulls the date of the API through
{{ job.date }}
What I need to work out to do and struggling with is
today - {{ job.date }} = Difference in Days
I have looked through the articles here but I have struggled to find one that I can understand.
Could this be done with twig?
Any help would be appreciated and even more so if someone could put the snippet together for me.
jQuery approach with help of this post
//split
var todayArr = ('11/03/2019').split('/');
var startDateArr = ('10/03/2019').split('/');
//change format
var today = `${todayArr[2]}-${todayArr[1]}-${todayArr[0]}`
var startDate = `${startDateArr[2]}-${startDateArr[1]}-${startDateArr[0]}`
//calculate
var diff = new Date(Date.parse(today) - Date.parse(startDate));
var days = diff/1000/60/60/24;
console.log(days);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can do something like this......
function countDays(firstDate, secondDate) {
var startDay = new Date(firstDate);
var endDay = new Date(secondDate);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = startDay.getTime() - endDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert(Math.floor(days));
}
If your date from api is "06/10/18" in "dd/mm/yy" format then
let date = "06/10/18";
let values = date.split("/");
date = new Date("20"+values[2],values[1]-1,values[0]);//months are from 0 to 11
let currDate = new Date();
let diff = currDate.getTime() - date.getTime();
diff = diff/1000; // seconds
diff = diff/60; // minutes
diff = diff/60; // hours
diff = diff/24; //days
let days = Math.round(diff);

How to use alert if the system date is changed?

How can I use alert if the date of system is changed in javascript. The date can be change manually of automatically.
[Thought is, Mainly client want to get an notification after day of end and start of the day. Total sales of today will be notified to the client when tomorrow is starting. like if the date of 30 and when it will be 31 and mail will be send to the client that you have sold sum quantity yesterday or date of 30]
Here I have tried this code. I am new in javascript so suggestion is needed.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
$("#today").change(function () {
alert(today);
});
You cannot listen to the event like you a trying, the only way you can do this is with a synthetic event that is fired when the date changes:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var changedate = function(date, to){
date = to;
document.trigger('dateChange');
}
document.on('dateChange', function () {
alert(today);
});

Set new date 12 months after in a form

I am very new to script and checked many answers but could not find the complete answer.
In a form, I have a start date, number of months and end date - I want to display the end date when the start date is entered - I have created this script but I must be missing something.
Here's my code:
[script type="text/javascript" src=Datejs][/js]
[script type="text/javascript" ]
window.onload = function() {
var startdateEl = document.getElementById("customFields_cf_232");
var leasetermEl = document.getElementById("customFields_cf_34");
var enddateEl = document.getElementById("customFields_cf_38");
function CalculateDate {
var enddateEl=leasetermEl.months().startdateEl;
}
var enddateEl.onblur = CalculateDate;
};
[/script]
I made this. It listens to your keystrokes live. http://jsfiddle.net/4t54J/
<input name="startDate" type="text" value="MM-DD-YYYY" />
<input name="endDate" type="text" />
var SECOND = 1000;
var MINUTE = SECOND * 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var YEAR = DAY * 365.25;
var startDateInput = 'input[name="startDate"]';
var endDateInput = 'input[name="endDate"]';
$(startDateInput).live('keypress', function (e) {
var startDate = $(startDateInput).val();
var endDate = setEndDate(startDate);
$(endDateInput).val(endDate);
});
function setEndDate(startDate) {
var date = new Date();
var parts = startDate.split('-');
if (date != '' && parts.length > 2) {
// year, month (0-based), day
date.setFullYear(parts[2], parts[0] - 1, parts[1]);
date.setTime(date.getTime() + YEAR);
var mm = date.getMonth() + 1;
mm = (mm < 10 ? '0' : '') + mm.toString();
var dd = date.getDate();
var yyyy = date.getFullYear();
return mm + "-" + dd + "-" + yyyy;
} else {
return '';
}
}

Javascript: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

Categories

Resources