Hi my problem is somewhat special or maybe not. However the problem is that I parse range of dates in one array, where I need to find start date and end date where ever it may occur in ranges. I do not know did I explain this well but if you need more info, please let me know.
e.g. [2010-7-11,2010-7-12,2010-7-13, 2010-9-01, 2010-9-02,....]
Now
2010-7-11 start and 2010-7-13 end
2010-9-01 start 2010-9-02 end
So on for entire ranges within array
Thanks in advance
Here's something quick and dirty. It expects the dates array to already be sorted in ascending order.
var dates = ["2010-7-11", "2010-7-12", "2010-7-13", "2010-9-01", "2010-9-02"],
startDates = [], endDates = [],
lastDate = null, date = null;
for ( var i=0, l=dates.length; i<l; ++i ) {
date = new Date(dates[i].replace(/-/g, "/"));
//
if ( !lastDate ) {
startDates.push(lastDate = date);
}
// If the diffrence between the days is greater than the number
// of milliseconds in a day, then it is not consecutive
else if ( date - lastDate > 86400000 ) {
lastDate = null;
endDates.push(date);
}
}
// Close the last range
endDates.push(date);
// Result is two symetical arrays
console.log(startDates, endDates);
Related
I am working on a system at the moment, that has rules based around dates ranges,
a user can submit a form, I need to check to date inputs fit within 1 of 3 dates ranges. Basically the 2 dates need to be within 1 of the 3 following rules,
01/01 - 30/04
01/05 - 30/09
01/10 - 31/12,
I need to workout what month the start date has and what month the end date has basically, and if the end date is outside of the it's range log it.
So basically, if a user submitted 01/01/2017 as a start date and 10/02/2017 as an end date, that would be a valid input, but if a user entered 01/01/2017 as a start date, and 01/06/2017 as end date that would be invalid as the date spans more than one date range.
Is it possible to check this kind of thing with javascript? I have gone through various scenarios, but the ranges in arrays and checking against array values, but I keep getting myself in a mess.
You can simply check if a date is in range with getTime()
JSBin
const isDateInRage = (startDate, endDate) => (dateToCheck) => {
return dateToCheck >= startDate && dateToCheck <= endDate
}
const isInRangeOne = isDateInRage('2016-01-01', '2016-04-30')
console.log('inRange', isInRangeOne('2016-01-02'))
console.log('outtOfRange', isInRangeOne('2016-07-02'))
Try this
// parse string 'XX/XX/XXXX' to create date object
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daysBetween(date1, date2) {
return Math.round((parseDate(date1)-parseDate(date2)) / (1000*60*60*24));
}
if(daysBetween('01/01/2017', '01/06/2017') > 1) {
// Your code here
}
Consider a function to test the start and end dates for each of the ranges and return true as soon as it fits in one of them. You'll need to correctly parse the strings, and also use the year from either the start or end date and apply it to the ranges.
The function below uses the start date and returns true if the start and end fit in one of the ranges, and false otherwise. If either the supplied start or end dates are invalid, it throws an error.
// Parse date in yyyy-mm-dd format as local date
function parseYMD(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Check start and end date are within one of the valid ranges
var checkInRange = (function () {
// Bespoke parser
function parsePart(p, y) {
p = p.split(/\D/);
return new Date(y, p[1]-1, p[0]);
}
// Valid ranges as d/m, year is taken from start date
var validRanges = ['01/01 - 30/04','01/05 - 30/09','01/10 - 31/12'];
return function (startDate, endDate) {
var dStart = parseYMD(startDate);
var dEnd = parseYMD(endDate);
// Throw error if input dates aren't valid
if (isNaN(dStart) || isNaN(dEnd)) {
throw new Error('start or end date is invalid')
}
var year = dStart.getFullYear();
// Return true if range is within valid ranges
return validRanges.some(function(range) {
var r = range.split(' - ').map(function(s){return parsePart(s, year)});
return dStart >= r[0] && dEnd <= r[1];
});
}
})();
// Some tests
[['2016-01-01','2016-04-30'],['2016-03-30','2016-04-30'],['2017-04-30','2017-05-01']].
forEach(function(dates) {
console.log('Start and end: ' + dates[0] + ' - ' + dates[1] +
'\nValid range?: ' + checkInRange(dates[0],dates[1]));
});
Do not use the Date constructor (or Date.parse) to parse strings. Their behaviour is largely implementation dependent. An ISO 8601 format date will be parsed as UTC, which is OK in this context as long as all of the strings are parsed identically, however if they aren't, users will
Here is my code to find whether the two given dates are equal or not ..
It should allow if today is small or equal. and it should not allow if it is greater date.
var date = '10-11-2015';
var today = '11-11-2016'
alert(today)
alert(date)
if( today <= date )
{
alert("small-or-equal-allow")
}
else
{
alert("larger-not-allow")
}
But its showing not working as expected for few days. What is the mistake and how can i fix it ?
You're comparing strings, not dates. If you want the values to be treated as dates then you need to cast them as dates...
var date = new Date('10-11-2015');
var today = new Date('11-11-2016');
if (today <= date) {
alert("small-or-equal-allow");
}
else {
alert("larger-not-allow");
}
edit, I've been able to work around this problem by comparing the values of the dates rather than the dates themselves:
$scope.entries[0].formattedDate === $scope.days[0]
$scope.entries[i].formattedDate.valueOf() === $scope.days[0].valueOf() //true
The goal of this angularjs program is to:
Generate the days in the current week (as an array of Javascript Date Objects)
Obtain a bunch of JSON objects from mongodb. (These objects have a property called "date." This "date" property is in the following format: ISODate("2016-05-18T04:44:42.067Z")
Compare each of the mongo items to a generated day, tell the user if any match (only the day! disregard time)
This is my code to generate the days of the week, and it works well:
$scope.getWeek = function (num) {
var curr = new Date;
curr.setDate(curr.getDate() - (num * 7));
var days = [];
for (var i = 0; i < 7; i++) {
days.push(new Date(curr.setDate(curr.getDate() - curr.getDay() + i)));
days[i].setHours(0, 0, 0, 0);
}
$scope.days = days;
};
I only want to know if the day matches, and not the time. I am using this function to strip the time from every item retrieved from Mongodb:
var removeHours = function (date) {
date.setHours(0, 0, 0, 0);
return date;
};
When it comes to comparing the dates, I'm absolutely stuck! It seems like I've tried everything. When I console.log the two dates, they are identical. I'm probably not aware of something about JS objects and I'm hoping somebody can provide a simple, easy solution.
$scope.entries[i].formattedDate == $scope.days[0] // false
I'm working on a followup question to one I posted here, which was resolved.
In my application, I am getting an array of values that are taken from a dynamic field on an input form (Gravity Forms List Field). A testing array that has the same structure can be created this way:
var entries = new Array();
entries[0] = new Array( 1, 1, 2016, "9:00", "am", "5:00", "pm");
entries[1] = new Array( 1, 2, 2016, "9:10", "am", "5:10", "pm");
From left to right, those values are: month, day, year, start time, star time period, end time, end time period.
Since it is a dynamic input - there could be any number of subarrays on a real submission.
My goal is to have an array of unix timestamps that I can use to do validations on the form submission. One validation will be 'is the current date more than 6 months past the last submitted date'.
The following code demonstrates how I am able to produce timestamps.
I'm looking for a method of adding an unlimited number of timestamps to my array.
I'm also looking for a method of targeting timestamps, once I have them.
// Create an array to collect timestamps
var sessions = new Array();
// Ready the Zero Prepend-er so dates are always correct
function twoDigitFormat( num ) {
return ( num.toString().length < 2 ? "0"+num : num ).toString();
}
// Loop through entries array to get each entry array
for ( i = 0; i < entries.length; i++ ) {
var entry = entries[i];
// Loop through each entry array to get the values
for ( j = 0; j < entry.length; j++ ) {
var value = entry[j];
// get all of the parts
var month = twoDigitFormat(entry[0]);
var day = twoDigitFormat(entry[1]);
var year = entry[2];
var stime = entry[3];
var stimeperiod = entry[4];
var etime = entry[5];
var etimeperiod = entry[6];
}
// Make Human Timestamps for each entry array
var sessionStartString = month+'-'+day+'-'+year+' '+stime+''+stimeperiod;
var sessionEndString = month+'-'+day+'-'+year+' '+etime+''+etimeperiod;
// I'm using moments.js for time handling
// Make Session Moments for each timestamp
var sStartMoment = moment( sessionStartString, "MM-DD-YYYY HH:mm a");
var sEndMoment = moment( sessionEndString, "MM-DD-YYYY HH:mm a");
// Make UNIX format moments for each timestamp
var sStartUnix = sStartMoment.unix();
var sEndUnix = sEndMoment.unix();
// Add each UNIX timestamp to the sessions array
// How do I add arrays with a variable as a key? I don't want to
// specify the key. Someone should be able to create 10 entries,
// or 20 entries, or .. whatever count.
sessions[0] = new Array ( sStartUnix );
sessions[1] = new Array ( sEndUnix );
}
// Get the current time (and as UNIX)
var now = moment();
var nowUnix = now.unix();
// Loop through sessions
for ( l = 0; l < sessions.length; l++ ) {
var session = sessions[l];
// How do I get things out of the array of timestamps?
// My current code results in session[key] being UNDEFINED?
var lastSession = session[session.length-1];
}
// Do stuff - like math, to run validations
// I know this isn't correct, but the idea will be to get
// a difference in hours
var lastNowDiff = nowUnix - lastSession;
if ( lastNowDiff > 4320 ) {
alert('The submission date must be within 6 months.');
}
I have it running in a Fiddle if you have a moment to check it out.
Use array's push method.
Example:
var entries = new Array();
entries.push(new Array( 1, 1, 2016, "9:00", "am", "5:00", "pm"));
You can add any number of arrays like this.
Complete Fiddle: https://jsfiddle.net/jryven/ovc2f1b7/
Use the JavaScript Date object for parsing and validating.
Is there any way in JavaScript that I can check if date is between 2 dates?
I have an array like
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
and now I have 2 dates like 1-7-2011 and 10-7-2011. I want to see if any value from unavailableDates falls between these date. If it falls it should return alert.
Can someone help me on this? I am in process of learning more about JavaScript and jQuery. I am not able to code it the way I understood the problem.
Here you have the solution
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
function str2date(sdate){ //This function gets a string and return a Date object
var parts = sdate.split("-");
return new Date(parts[2], parseInt(parts[1], 10)-1, parts[0]);
}
var stamp1 = str2date("1-7-2011").getTime(); //First date. getTime() converts it to an integer
var stamp2 = str2date("10-7-2011").getTime(); //Second date
for(var i=0; i<unavailableDates.length; i++){
var curStamp = str2date(unavailableDates[i]).getTime();
if(curStamp >= stamp1 && curStamp <= stamp2) //Check if it falls in range
alert(unavailableDates[i] + " falls in range");
}
Hope this helps. Cheers
Date object in JavaScript allows compare operation, you only required to have proper Date objects. Create Date objects from your bounds and array members and compare them in a loop.
More information about Date object could be found there: http://www.w3schools.com/js/js_obj_date.asp