How to compare two different dates in dd/mm/yyyy format - javascript

Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa

Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}

Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);

Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.

The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...

Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());

if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this

Related

Im having trouble with Month comparison in JS

I am trying to compare months from a form, which are 1,2,3,4,5,6,7,8,9,10,11,12 to getMonth()
I have been trying to figure it out for a while, and tried parsing to Int and making sure the Int's
are the same, i.e. single digits, but to no effect.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth"));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear"));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
The year comparison works fine, but the second if statement will not work for some reason unknown to me.
you need to check year, cardYear, cardMonth & month first !
for this you have to log all these variables.
and you did not get the value of these two given lines
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var cardYear = parseInt(document.getElementById("cardyear").value));
now you can try this code and let me if its work fine.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear").value));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
console.log(`${year} === ${cardYear} && ${cardMonth} < ${month}`)
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
I fixed it by changing the html value properties. It was reading the value and not what was between the tags as I had thought.
I tried using this:
var demo = document.getElementById("demo");
demo.innerHTML=month+" "+cardMonth+" "+year+" "+cardYear;
To print the values and troubleshooted as I don't have breakpoints in notepad++.
Thanks for giving me the idea.

How to get specific year from the Date field in jquery

I know its a bit silly question, but I actually wanted to know how can I retrieve the year value for a date that I already have without using the "Split" function. I can achieve it with the help of the "split" function. Below is the code that I used in jquery.
outputJSon = JSON.parse($('#' + Datepicker_id).val());
var currentYear = parseInt(CalculateYearfromString($('#' + currentActivityCalendarId).parents('.service-timeline').find('.membership-year .period').text()));
if (currentYear === undefined && $.trim(currentYear) === "")
currentYear = new Date().getFullYear();
if (parseInt(outputJSon["Date"].split('/')[0]) === currentYear)
outputDate = outputJSon["Date"];
else
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[0], currentYear)
outputDateType = outputJSon["DateType"];
In the above code, I am retrieving the date value in a JSON format which returns Date eg. 2016/05/26 and DateType eg. Day.
I am fetching the current year that I have selected and then checking if currentYear value is equal to the year that I have in the outputJSon["Date"]. If there is a match, then I am replacing the [0] value of the outputJSon["Date"] with the currentYear, with the help of replace function. This works as expected and no error is encountered.
I just want to be sure that if the date format changes(from 2016/05/26 to 26/05/2016)**then the split function that I have written will retrieve wrong value. How can I avoid this. Shall I remove **split function and think of something else?
Any help is appreciated.
Thanks,
Totally unsexy, but what's wrong with indexOf?
if (outputJSon["Date"].indexOf(currentYear) != -1) {
// currentYear is in the string somewhere
}
Note also that in the original, there is no need for parseInt:
outputJSon["Date"].split('/')[0] == currentYear
is sufficient (and less to type).
Also, parseInt will never return undefined, so:
currentYear === undefined
will always be false and so:
if (currentYear === undefined && $.trim(currentYear) === "")
will never be true and the assignment:
currentYear = new Date().getFullYear();
will never execute.
I would also seriously question the use of:
outputJSon = JSON.parse($('#' + Datepicker_id).val());
The use of JSON.parse seems entirely gratuitous, you already have a string returned by $('#' + Datepicker_id).val().
You can check the length to make sure it is a valid year number.
currentYear2 = outputJSon["Date"].split('/');
currentYear2 = (currentYear2[0].length === 4) ? currentYear2[0] : currentYear2[2];
Is there any issues when you simply do
outputDate = new Date(outputJSon["Date"]).getFullYear();
You can try something like this:
JSFiddle.
Code
function getYear() {
var input = $("#dpDate").val();
var cdate = getDate(input);
console.log(cdate, cdate.getFullYear());
}
function getDate(input) {
var arr = [];
var seperator = ['/', '-'];
var year, month, date;
var yearIndex = 2;
var result = undefined;
seperator.forEach(function(s) {
if (input.indexOf(s) > -1)
arr = input.split(s);
});
if (arr.length > 1) {
// Set year
if (arr[0] > 1000) {
year = arr[0]
yearIndex = 0;
} else if (arr[2] > 1000) {
year = arr[2];
yearIndex = 2;
}
// set month and date
// If string starts with year, assume yyyy/mm/dd
if (yearIndex === 0) {
month = arr[1]
date = arr[2]
} else {
// If value greater than 12, assume it as date and other one as month
if (arr[0] > 12) {
date = arr[0]
month = arr[1]
} else if (arr[1] > 12) {
date = arr[1]
month = arr[0]
}
// If none of the value is ggreater than 12, assume default format of dd/mm/yyyy
else {
date = arr[0]
month = arr[1]
}
}
result = new Date(year, month - 1, date);
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="dpDate" type="text" placeholder="dd/mm/yyyy" value="15/2/2016" />
<button onclick="getYear()">Get Year</button>
regex_yearfirst = /\d{4}\W/;
regex_yearlast = /\d{4}\n/;
if (regex_yearfirst.test(outputJSon["Date"])) {
yearIndex=0;
}
else if (regex_yearlast.test(outputJSon["Date"])) {
yearIndex=2;
}
else {
console.log("date format not recognized")
}
if (parseInt(outputJSon["Date"].split('/')[yearIndex]) === currentYear) {
outputDate = outputJSon["Date"];
}
else {
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[yearIndex], currentYear)
}

Sort a string date array

I want to sort an array in ascending order. The dates are in string format
["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"]
Even need a function to check whether these dates are in continuous form:
eg - Valid - ["09/06/2015", "10/06/2015", "11/06/2015"]
Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"]
Example code:
function sequentialDates(dates){
var temp_date_array = [];
$.each(dates, function( index, date ) {
//var date_flag = Date.parse(date);
temp_date_array.push(date);
});
console.log(temp_date_array);
var last;
for (var i = 0, l = temp_date_array.length; i < l; i++) {
var cur = new Date();
cur.setTime(temp_date_array[i]);
last = last || cur;
//console.log(last+' '+cur);
if (isNewSequence(cur, last)) {
console.log("Not Sequence");
}
}
//return dates;
}
function isNewSequence(a, b) {
if (a - b > (24 * 60 * 60 * 1000))
return true;
return false;
}
The Simple Solution
There is no need to convert Strings to Dates or use RegExp.
The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
Update:
A helpful comment suggested using localeCompare() to simplify the sort function. This alternative is shown in the above code snippet.
Run Snippet to Test
<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>
You will need to convert your strings to dates, and compare those dates, if you want to sort them. You can make use of the parameter that the sort method accepts, in order to achieve this:
var dateStrings = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedStrings = dateStrings.sort(function(a,b) {
var aComps = a.split("/");
var bComps = b.split("/");
var aDate = new Date(aComps[2], aComps[1], aComps[0]);
var bDate = new Date(bComps[2], bComps[1], bComps[0]);
return aDate.getTime() - bDate.getTime();
});
In order to reduce code redundancy, and to handle different date formats, you can add an additional function that will create the comparator needed by the sort method:
function createSorter(dateParser) {
return function(a, b) {
var aDate = dateParser(a);
var bDate = dateParser(b);
return aDate.getTime() - bDate.getTime();
};
}
dateStrings.sort(createSorter(function(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}));
You can then use different date formatters by passing different functions to the createSorter call.
As for your second question, you can create an (sorted) array of dates from your strings, and perform your logic on that array:
function myDateParser(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}
var sortedDates = dateStrings.map(myDateParser).sort();
You can walk through the sortedDates array and if you find two non-consecutive dates, then you have dates with gaps between them.
var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
function dmyOrdA(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function dmyOrdD(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
function mdyOrdA(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function mdyOrdD(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
dateArray = new Array("09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015");
var c = dateArray.sort( dmyOrdA );
console.log(c);
To sort your date string ascendingly without alteration to its value, try this:
var T = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedT = T.sort(s1,s2){
var sdate1 = s1.split('/');
var sdate2 = s2.split('/');
var date1 = s1[1]+'/'+s1[0]+'/'+s1[2];
var date2 = s2[1]+'/'+s2[0]+'/'+s2[2];
if (Date.parse(date1) > Date.parse(date2)) return 1;
else if (Date.parse(date1) < Date.parse(date2) return -1;
else return 0;
}
The resultant array sortedT should be a sorted array of date string.
NOTE:
Your date format is stored in dd/mm/yyyy but the standard date format of JavaScript is mm/dd/yyyy. Thus, in order to parse this string to Date without using external date format library, the date string is therefore needed to be converted for compatibility during sort.

how to calculate values of an (javascript) object with date keys

I have the following simplified (javascript) object, of which properties are dates (in string fomat):
Given a random startdate and enddate within the range of dates in the object, how to code (efficiently) the calculation - say accumulate- of the values within this range? As an example, for the following code the calculation result should be 12 (3+4+5) for the given startdate and enddate.
var startdate = '2014-01-03';
var enddate = '2014-01-05'
var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';
You can just loop through the properties of the object, doing a comparison, and adding.
var startdate = '2014-01-04';
var enddate = '2014-01-05';
var arr = {};
arr['2014-01-02'] = '2';
arr['2014-01-03'] = '3';
arr['2014-01-04'] = '4';
arr['2014-01-05'] = '5';
arr['2014-01-06'] = '6';
var total = 0;
for(var p in arr) {
if(arr.hasOwnProperty(p)) {
if(new Date(p) >= new Date(startdate) && new Date(p) <= new Date(enddate)) {
total += parseInt(arr[p], 10);
}
}
}
console.log(total);
Sample http://jsbin.com/imUdewaJ/1/edit
I'm sure there is a better way to do this, but I don't know how due to having to parse the date object out for comparison.
--Edit added in the hasOwnProperty check from comments below
When doing stuff with dates, you might want to use thirdparty tools to handle browser compatibility. Momentjs is a good one for dates.
solution with momentjs:
var startdate = moment('2014-01-03');
var enddate = moment('2014-01-05');
var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';
var strDate;
var total = 0;
for (strDate in obj) {
if (obj.hasOwnProperty(strDate)) {
var date = moment(strDate)
if (date.diff(startdate, 'days')>=0 && date.diff(enddate, 'days')<=0) {
total += parseInt(obj[strDate], 10);
}
}
}
console.log(total);
It's possible that some browsers won't support date1 > date2, so it might be better to also use getTime().
function getDate(date) {
return new Date(date).getTime();
}
function getTotal(start, end) {
var total = 0;
for (var k in obj) {
var current = getDate(k);
if (current >= start && current <= end) {
total += parseInt(obj[k], 10);
}
}
return total;
}
var start = getDate(startdate);
var end = getDate(enddate);
console.log(getTotal(start, end)); // 12

Loop from startdate to enddate from inputs with javascript

I've got a startdate and enddate from inputs. And I need to put all the dates from the startdate until the enddate into the database. Therefore I need to make a loop like this:
FOR i = startdate; i <= enddate; i + 1 day
{
here i use the date
}
How do I make such a loop with dates from input boxes?
I get 'invalid date' if I try to do this:
var endDate = new Date($("#enddate").val());
And I can't use the endDate.getTime() like I need as you said in the answer, if I do it like this.
var endDate = $("#enddate").val());
var endDateTime = endDate.getTime();
So basically: How can I convert the input to a date? The input of enddate is like this: dd/mm/yyyy.
No it's not an SQL question, I need to do this is javascript because I need to check the dates first.
Thank you for helping me out ;)
Would a loop like this work?:
var current_date = new Date("01/13/2013");
var end_date = new Date("01/20/2013");
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
console.log(current_date);
current_date.setDate(current_date.getDate()+1);
}
http://jsfiddle.net/Sn6Ws/
Depending on the format of your textboxes' values, you can set it up like this:
$(document).ready(function () {
$("#btn").on("click", function () {
dateLooper(function (cur, end) {
console.log("Current date: " + cur.toString() + ", End Date: " + end.toString());
});
});
});
function dateLooper(callback) {
var start_date_text = document.getElementById("start_date").value;
var end_date_text = document.getElementById("end_date").value;
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
//console.log(current_date);
callback.call(this, current_date, end_date);
current_date.setDate(current_date.getDate()+1);
}
}
http://jsfiddle.net/Sn6Ws/1/
Per your comments that explain the date are in the format "dd/mm/yyyy", you could use something like this:
var start_date_text = document.getElementById("start_date").value;
var start_split = start_date_text.split("/");
if (start_split.length != 3) {
return false;
}
start_date_text = start_split[1] + "/" + start_split[0] + "/" + start_split[2];
var end_date_text = document.getElementById("end_date").value;
var end_split = end_date_text.split("/");
if (end_split.length != 3) {
return false;
}
end_date_text = end_split[1] + "/" + end_split[0] + "/" + end_split[2];
to get the dates in the right format before passing them to new Date. Here's an updated jsFiddle that demonstrates it:
http://jsfiddle.net/Sn6Ws/4/
Of course, be careful that if the dates don't come in with the specified format (in case users can type this in or something), the code will most likely throw an error. You can obviously put more checks in to make sure certain things set before proceeding with certain operations (like making sure each item is a number/integer, making sure the days are in the range 1 to 31, etc.). So for that reason, you may want to go the route of regular expressions. At least with regular expressions, you can specify a specific pattern and know whether it matches perfectly or not, and immediately get the values you need to build a date.
Using regular expressions, here's an example that isn't complete but should hopefully help:
function dateLooper(callback) {
var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var start_date_text = document.getElementById("start_date").value;
var start_match = re.exec(start_date_text);
if (start_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate start_match[1] is valid day
// Validate start_match[2] is valid month
// Validate start_match[3] is valid year
if (valid) {
start_date_text = combineDate(start_match);
} else {
return false;
}
} else {
return false;
}
var end_date_text = document.getElementById("end_date").value;
var end_match = re.exec(end_date_text);
if (end_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate end_match[1] is valid day
// Validate end_match[2] is valid month
// Validate end_match[3] is valid year
if (valid) {
end_date_text = combineDate(end_match);
} else {
return false;
}
} else {
return false;
}
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
var days_spent = 0;
while (current_date.getTime() < end_date_time) {
days_spent++;
callback.call(this, current_date, end_date, days_spent);
current_date.setDate(current_date.getDate()+1);
}
return days_spent;
}
function combineDate(re_match) {
return re_match[2] + "/" + re_match[1] + "/" + re_match[3];
}
http://jsfiddle.net/Sn6Ws/6/

Categories

Resources