Those who still looking for a solution on how to disable past date click on Dateclick event on FullCalendar. can try see solution below, if any of the reader had other idea can post other solution below. It would be much better if there is another easy way. The more solution, the better it would be.
It's possible to improve on your string-manipulation of dates, by doing a simple comparison as follows:
dateClick: function (info) {
var clickedDate = getDateWithoutTime(info.date);
var nowDate = getDateWithoutTime(new Date())
if (clickedDate >= nowDate) alert("Future date");
else alert("Past date");
}
It is helped by this function:
//get date without the time of day
function getDateWithoutTime(dt)
{
dt.setHours(0,0,0,0);
return dt;
}
Demo: https://codepen.io/ADyson82/pen/ZErwJGx
One other option to achieve the same goal is to use the validRange functionality. This lets you dynamically set a start date, before which all dates are disabled:
validRange: function (nowDate) {
return {
start: nowDate
};
},
Demo: https://codepen.io/ADyson82/pen/VwQgWJO
The slight downside of this though is that it also hides any events which occur before the current date - you may not want this.
Therefore, another alternative is to use selectAllow to restrict where the user can select. Note that this relies on you using the select callback rather than dateClick - but that should not be a big problem.
selectAllow: function (info) {
return (info.start >= getDateWithoutTime(new Date()));
}
Demo: https://codepen.io/ADyson82/pen/VwQgzZJ
Below is just my current solution to disable past date on FullCalendar. Any idea or improvement would be appreciate to improve the code below.
dateClick: function(e) {
// Get Today
var dt = calendar.getDate();
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
if(month < 9){
month = '0'+month;
}
if(day < 9){
day = '0'+day;
}
var today = year + '-' + month + '-' + day;
// Get Selected Date
var check = e.dateStr;
let A = today.toString();
let B = check.toString();
alert('Date A: ' + A );
alert('Date B: ' + B );
if(B >= A){
alert('Past Date');
}
else{
alert('Future Date');
}
},
Related
I need the date of last September with moment.js - but dynamically.
Current Date
currentDate:string = moment().format('YYYY-MM'); // This will be 2017-10
How to know when the last september was from the current date? I need somethink like this:
lastSteptember = moment(this.currentDate).getDateOfLast('september').format('YYYY-MM');
So the result from now would be:
2017-09
But 3 months ago the result would have been another:
2016-09
How do I can handle this with moment.js?
I dont know how to make it work with moment. But you can use my function to get last month by month number:
var getLastMonth = function(month){
if(month<1 || month>12) return undefined;
let year = (month<=moment().month())? (moment().year()) : (moment().year()-1);
return moment(month + "-" + year, "MM-YYYY");
}
Use it:
getLastMonth(11); //return 11-2016
getLastMonth(10); //return 10-2017
getLastMonth(9); //return 09-2017
I found a pretty solution and solved it like this:
currentYear: number = moment().year();
lastYear: number = moment().subtract(1, 'years').year();
nextYear: number = moment().add(1, 'years').year();
if(moment().isSameOrAfter(this.currentYear + '-09-01', 'month')) {
this.currentServiceYearStartDate = this.currentYear + '-09-01';
this.currentServiceYearEndDate = this.nextYear + '-08-31';
} else {
this.currentServiceYearStartDate = this.lastYear + '-09-01';
this.currentServiceYearEndDate = this.currentYear + '-08-31';
}
console.log('Startdate: ' + this.currentServiceYearStartDate);
console.log('Enddate: ' + this.currentServiceYearEndDate);
https://momentjs.com/docs/#/query/is-same-or-after/
This function will return the month of the previous year if the given month is lower than the current month, otherwise it will return the month with the current year.
function getMonthWithPresentOrPastYear(month, format) {
currentMonth = parseInt(moment().format('M'));
givenMonth = parseInt(moment().month(month).format('M'));
format = format || 'YYYY-MM';
return (givenMonth >= currentMonth) ?
moment().month(month).format(format) : // Present
moment().month(month).subtract(1, 'year').format(format); // Past
};
getMonthWithPresentOrPastYear('January'); // returns '2016-01'
getMonthWithPresentOrPastYear('September'); // returns '2016-09'
getMonthWithPresentOrPastYear('October'); // returns '2017-10'
getMonthWithPresentOrPastYear('December', 'YYYY/DD'); // returns '2017/12'
You can try the following :
Object.getPrototypeOf(moment()).getLast = function(month,format="YYYY-MM"){
var date;
if(this.diff("01 "+month+" "+this.year()) >= 0 || this.format("MMMM").toLowerCase() === month.toLowerCase)
date = moment(this).month(month);
else
date = moment(this).month(month).subtract(1,"years");
return date.format(format);
});
In the above JavaScript we check whether the month has passed in the current moment object.
This allows us to directly check from any moment object and of any month eg:
var customDate = moment("01 December 2001");
customDate.getLast("September"); //"2001-09"
I have a jQuery datepicker and I need to do the following:
Disable all Sundays between a specific date range
I understand I need to use the beforeShowDay function but cannot seem to get it in place using the other answers and examples on Stack Overflow.
Any help would be great.
Dan
If it's a static set of sundays, you can simply use an array with the dates you want to disable [taken from Jquery UI datepicker. Disable array of Dates ]:
var array = ["2013-03-14","2013-03-15","2013-03-16"]
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
If you want to make a dynamic set of sundays, you'll have to create a function to get an array of Sundays from a start date and an end date.
Here is a function to do exactly that:
function addSundaysToArray(fromDate, toDate, datesToDisable){
fromDate = new Date(fromDate);
toDate = new Date(toDate);
while(fromDate < toDate){
fromDate.setDate(fromDate.getDate() + 1);
if(fromDate.getDay() === 0){
var year = fromDate.getFullYear();
var month = fromDate.getMonth() + 1;
month = (month + '').length == 1 ? '0' + month : month;
var day = fromDate.getDate();
day = (day + '').length == 1 ? '0' + day : day;
datesToDisable.push(year + "-" + month + "-" + day);
}
}
}
Obviously you can use actual date objects here or even milliseconds. Or you can skip the array input to the function and just return an array with the dates.
I chose to represent the dates as yyyy-mm-dd since most of the times humans read these arrays and it's better to have them readable. Of course, if readability is not that important to you, you can just keep the dates in whatever format you prefer.
I was browsing through the net to find a javascript function
which can check whether the date entered by the user is current date or the future date but i didn't found a suitable answer so i made it myself.Wondering If this can be achieved by one line code.
function isfutureDate(value)
{
var now = new Date;
var target = new Date(value);
if (target.getFullYear() > now.getFullYear())
{
return true;
}
else if(target.getFullYear() == now.getFullYear())
{
if (target.getMonth() > now.getMonth()) {
return true;
}
else if(target.getMonth() == now.getMonth())
{
if (target.getDate() >= now.getDate()) {
return true;
}
else
{
return false
}
}
}
else{
return false;
}
}
You can compare two dates as if they were Integers:
var now = new Date();
if (before < now) {
// selected date is in the past
}
Just both of them must be Date.
First search in google leads to this: Check if date is in the past Javascript
However, if you love programming, here's a tip:
A date formatted like YYYY-MM-DD could be something like 28-12-2013.
And if we reverse the date, it is 2013-12-28.
We remove the colons, and we get 20131228.
We set an other date: 2013-11-27 which finally is 20131127.
We can perform a simple operation: 20131228 - 20131127
Enjoy.
here's a version that only compares the date and excludes the time.
Typescript
const inFuture = (date: Date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
ES6
const inFuture = (date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
try out this
function isFutureDate(idate){
var today = new Date().getTime(),
idate = idate.split("/");
idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
return (today - idate) < 0 ? true : false;
}
Demo
console.log(isFutureDate("02/03/2016")); // true
console.log(isFutureDate("01/01/2016")); // false
ES6 version with tolerable future option.
I made this little function that allows for some wiggle room (incase data coming in is from a slightly fast clock for example).
It takes a Date object and toleranceMillis which is the number of seconds into the future that is acceptable (defaults to 0).
const isDistantFuture = (date, toleranceMillis = 0) => {
// number of milliseconds tolerance (i.e. 60000 == one minute)
return date.getTime() > Date.now() + toleranceMillis
}
try this
function IsFutureDate(dateVal) {
var Currentdate = new Date();
dateVal= dateVal.split("/");
var year = Currentdate.getFullYear();
if (year < dateVal[2]) {
return false;//future date
}
else {
return true; //past date
}
}
In my case, I used DD-MM-YYYY format dates to compare and it gives an error since the behaviour of "DD-MM-YYYY" is undefined. So I convert it to a compatible format and compare it. And also if you need to compare only the dates and not time, you need to set time parameters to zero.
var inputDateVal = "14-06-2021";
if (inputDateVal != null && inputDateVal != '') {
var dateArr = inputDateVal.split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if(inputDate > toDay){
console.log("Date is a future date");
}else if(inputDate== toDay){
console.log("Date is equal to today");
}else{
console.log("Date is a past date");
}
}
You can use moment.js library
let dateToBeCompared = "10/24/2021"; // "DD/MM/YYYY" format
// For past dates
moment(dateToBeCompared, "DD/MM/YYYY").isBefore(moment(new Date(), "DD/MM/YYYY"),
'day')
// For same dates
moment(dateToBeCompared, "DD/MM/YYYY").isSame(moment(new Date(), "DD/MM/YYYY"),
'day')
// For future dates
moment(dateToBeCompared, "DD/MM/YYYY").isAfter(moment(new Date(), "DD/MM/YYYY"),
'day');
There are other functions like also like isSameOrAfter() and isSameOrBefore()
Have a look at here
I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012"; // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}
We have a .NET web service which returns JSON, including a date in string format as follows: 2012-04-30T00:00:00+12:00.
In javascript, I want to exclude dates where the month is not the current month. Hence, with the above date, the month is 04 (April) and the current month is May (in New Zealand anyway). So, I want to ignore this record, e.g, in pseudocode:
if(vMonth == CurrentMonth){
dothis();
}
How can I do this?
EDIT: See Rob G's answer below for the solution that works in all browsers.
var dateOne = new Date("2012-04-30T00:00:00+12:00");
var dateTwo = new Date();
if(dateOne.getMonth() == dateTwo.getMonth()) {
alert("equal");
}
Here's the jsfiddle:
http://jsfiddle.net/Mq5Tf/
More info on the date object:
MSDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
ES5: http://es5.github.com/#x15.9.2
var date = new Date();
var currentMonth = date.getMonth();
var yourMonth = 4;
if(yourMonth == currentMonth ){
/* Do this */
alert('Hello');
}
An alternative that doesn't depend on parsing the date string:
function checkMonth(ds) {
var now = new Date();
var m = now.getMonth() + 1;
return !!ds.match(now.getFullYear() + '-' + (m<10?'0':'') + m);
}
// on 2012-05-01
alert( checkMonth('2012-04-30T00:00:00+12:00') ); // false
alert( checkMonth('2012-05-01T00:00:00+12:00') ); // false
Edit
Note that checking the month number only works where the timezone offset should be ignored or is not significant. While 2012-04-30T00:00:00+12:00 is in April, 2012-04-30T14:00:00+12:00 will be 2am on 1 May local time.
// Means April 30, months are indexes in JS
var input = new Date(2012, 03, 30);
// or use format new date("2012-04-30T00:00:00+12:00") suggested in other answer
var currentDate = new Date();
if(input.getFullYear() == currentDate.getFullYear() // if you care about year
&& input.getMonth() == currentDate.getMonth()) {
// act accordingly
}