I am trying to use React Datepicker in my React application. I am following this document - https://reactdatepicker.com/
I need a date picker which will only show 31 days.
Here is the simple code from the react-datepicker documents.
<DatePicker selected={dayPicker} onChange={(date) => setDayPicker(date)} dateFormat="yyy/MM/dd" isClearable={true}
/>
It shows the full calendar. How can I customize the calendar ? Is it possible to remove the header from the calendar and replace it with a text "Days" ?
Following code will give you date picker for current year with only Month in header.
You just need to use renderCustomHeader property of DatePicker.
const year = 2022; // can be provided externally
const month = 2; // can be provided externally
const date = 24; // can be provided externally
const [startDate, setStartDate] = useState(new Date(year, month, date));
const minDate = new Date(year, month, 1);
const maxDate = new Date(year, month + 1 , 0);
const renderDayContents = (day, date) => {
if(date < minDate || date > maxDate){
return <span></span>;
}
return <span>{date.getDate()}</span>;
};
return (
<DatePicker
selected = {startDate}
minDate = {minDate}
maxDate = {maxDate}
onChange = {(date) => setStartDate(date)}
renderCustomHeader = {() => <div></div>}
renderDayContents = {renderDayContents}
dateFormat = "dd"
/>
);
This is how it will look:
Explaination:
We can create out customer header with the renderCustomHeader property of DatePicker.
This functions returns JSX (kind of html) which has empty div as we don't want to show anything in header.
Apart from renderCustomHeader property, we have set minDate and maxDate property of DatePicker to restrict it for current month.
You need to copy above code in a component where you are using DatePicker.
You can refer https://reactdatepicker.com/#example-custom-header to know more about custom header for DatePicker
Related
How to disable the past dates in the Kendo date picker ? ( Date Picker validation)
That will allow the user to select only the current date and future date.
In the HTML :
#Html.EditorFor(Model => Model.AppointmentDate)
In the JQuery :
$('#AppointmentDatee').data('kendoDatePicker')
The shortest way to disable past dates is using min parameter with current date value:
var presentDate = new Date();
$(function () {
var datepicker = $('#AppointmentDate').kendoDatePicker({
value: presentDate,
min: presentDate,
}).data('kendoDatePicker');
});
If you're using Razor with #Html.Kendo() helper, use DatePickerBuilderBase.Min() method:
#(Html.Kendo().DatePicker().Name("AppointmentDate").Min(DateTime.Today))
However, the min parameter will remove all disabled past dates (i.e. they're not shown in calendar view). If you want to show disabled dates but the user cannot interact with them (by clicking the date), use k-state-disabled CSS class in empty option inside month parameter:
var datepicker = $('#AppointmentDate2').kendoDatePicker({
value: presentDate,
min: presentDate,
month: {
empty: '<div class="k-state-disabled">#= data.value #</div>'
}
}).data('kendoDatePicker');
If #(Html.Kendo()) helper is used, use DisabledDates to call a function which disables past dates like example below:
<script>
var getPastDates = function(begin, end) {
for (var dtarr = [], date = start; date < end; date.setDate(date.getDate() + 1)) {
dtarr.push(new Date(dt));
}
return dtarr;
}
function disablePastDates(date) {
var pastDate = getPastDates(new Date('0001-01-01T00:00:00Z'), new Date());
if (date && compareDates(date, dates)) {
return true;
}
else {
return false;
}
}
function compareDates(date, dates) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getDate() == date.getDate() &&
dates[i].getMonth() == date.getMonth() &&
dates[i].getYear() == date.getYear()) {
return true;
}
}
}
</script>
Helper usage:
#(Html.Kendo().DatePicker().Name("AppointmentDate").DisableDates("disablePastDates"))
Working examples:
JSFiddle demo 1 (hidden past dates)
JSFiddle demo 2 (grayed-out past dates)
References:
Kendo.Mvc.UI.Fluent.DatePickerBuilderBase.Min(DateTime)
Show Out-of-Range Dates as Disabled
Kendo MVC DatePicker - Disable dates
Similar issue (with different approach):
How to disable past dates without hiding them in Kendo date picker?
if you use jquery for your kendoDatePicker , this code may help you!
$("#MyDatapickerElement").kendoDatePicker({
value: new Date(),
disableDates: function (date) {
if (date <= new Date()) {
return true;
} else {
return false;
}
}
});
If using Html.Kendo().DatePicker() you can show the disabled dates using the MonthTemplate. Example below shows the Minimum Date set to DateTime.Today and sets the MonthTemplate to show past dates as disabled.
Html.Kendo().DatePicker()
.Name("MyDate")
.Min(DateTime.Today)
.MonthTemplate(m=>m
.Empty("<div class=\"k-state-disabled\">#= data.value #</div>")
)
I would like to ask if is possible set "FROM" and "TO" in the highchars/Stock.
I am using YEAR, so I would like to load the year but in the Input FROM and TO set a value dynamically with number after a calculation.
Is this possible?
Thank you.
1.Update:
With:
var minDate = $('input.highcharts-range-selector:eq(0)').val();
var maxDate = $('input.highcharts-range-selector:eq(1)').val();
I can get the date, but to set should be different.
var dateCurrent = new Date();
events:{
load:function(){
this.xAxis[0].setExtremes(
Date.UTC(2000, 0, 1), dateCurrent
);
}
}
Just use setExtremes().
My model class property looks like this
public DateTime PurchaseDate { get; set; }
and inside view
#Html.TextBoxFor(model => model.PurchaseDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.PurchaseDate)
and I am giving a date like this in form
19/06/2015
But it gives validation message and not allows page to be submitted, message is like this
The field PurchaseDate must be a date.
if I give date in mm/dd/yyyy format it works. Can anyone point out what I am doing wrong here?
The client side error is occurring because by default jquery.validate tests the value using the MM/dd/yyyy format. You can override the $.validator.addMethod('date', function (value, element) function to test that the value is in the dd/MM/yyyy you expect. Note the following code is from my own jquery plugin associated with a #Html.DatePickerFor() helper method which renders a data-dateformat attribute in the output based on the servers culture, so it may be an overkill for your needs
Add the following scripts (not in document.ready, but after jquery.validate.unobtrusive)
Date.prototype.isValid = function () {
return !isNaN(this.getTime());
}
globalDate = function (value, formatString) {
// Initialise a new date
var date = new Date(0);
if (value == undefined) {
// Return todays date
return date;
}
// Get the components of the format
// The separator can be forward slash, hyphen, dot and/or space
var regex = new RegExp(/([dMy]+)([\s/.-]+)([dMy]+)([\s/.-]+)([dMy]+)/);
//var format = regex.exec(this.inputFormat);
var format = regex.exec(formatString);
// Get the components of the value
regex = new RegExp(/(\d+)([\s/.-]+)(\d+)([\s/.-]+)(\d+)/);
value = regex.exec(value);
// Check the value is valid
if (value === null || value[2] !== format[2] || value[4] !== format[4]) {
// Its not valid
date.setTime(Number.NaN);
return date;
}
// TODO: What if year entered as 2 digits?
var day = Number.NaN;
var month = Number.NaN;
var year = Number.NAN;
if (format[1].charAt(0) === 'd') {
// little-endian (day, month, year)
day = parseInt(value[1]);
month = parseInt(value[3]) - 1;
year = parseInt(value[5]);
} else if (format[1].charAt(0) === 'M') {
// middle-endian (month, day, year)
day = parseInt(value[3]);
month = parseInt(value[1]) - 1;
year = parseInt(value[5]);
} else {
// big endian (year, month, day)
day = parseInt(value[5]);
month = parseInt(value[3]) - 1;
year = parseInt(value[1]);
}
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
// Check its valid
if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
date.setTime(Number.NaN);
return date;
}
return date;
}
$.validator.addMethod('date', function (value, element) {
var format = "dd/MM/yyyy";
return this.optional(element) || globalDate(value, format).isValid();
}
If you only ever want to test for the format dd/MM/yyyy, then you could simplify the globalDate() function by just using
var date = new Date();
date.setHours(0, 0, 0, 0);
var components = value.split('/');
var day = components[0];
var month = components[1];
var year = components[2];
date.setFullYear(year);
....
Edit
Further to OP's comments regarding server side validation failing, the server culture needs to accept a date string in the format dd/MM/yyyy. In the web.config.cs file
<system.web>
<globalization culture="en-AU" uiCulture="en-AU"/> // adjust to your culture code
....
If you want to explicitly set the expected date format for your model property then you can do this using the DisplayAttribute
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PurchaseDate { get; set; }
Otherwise, the current culture of the server would be used (which in your case happens to be MM/dd/yyyy).
It appears that in order for client-side validation to respect the DataFormatString we need to use EditorFor in place of TextBoxFor
#Html.EditorFor(model => model.PurchaseDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.PurchaseDate)
I have updated my project to version 2013.3.1324 from 2013.3.1119 (with ASP.NET MVC wrappers)
And I saw the following after update:
DateTime is passed to the client as
"/Date(-498283200000)/"
if less than 1970 year and
"/Date(498283200000)/"
if more that 1970 year
I have found a strange code in the kendo.all.js file
dateRegExp = /^\/Date\((.*?)\)\/$/,
tzOffsetRegExp = /[+-]{1}\d+/,
...
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
date = date[1];
tzoffset = tzOffsetRegExp.exec(date);
date = parseInt(date, 10);
if (tzoffset) {
date -= (parseInt(tzoffset[0], 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}
Debug info:
Initial value:
Parsed date value:
Parsed tzo value:
And finally, result date value:
Actually I don't need time, only Date. Model property type is regular DateTime.
Also I can't find any issues with this release on the Kendo site.
What I'm doing wrong and what I need to do? (changing Kendo source is not an option I think...)
Example:
Live demo: http://jsbin.com/vebed/2/edit?html,js,output
The following:
alert(kendo.parseDate("/Date(-498283200000)/"))
shows
Thu Mar 18 1954 22:00:00 GMT+0200 (FLE Standard Time)
with the latest official version of Kendo UI.
Make sure you are not using an older version.
Here is a live demo: http://jsbin.com/vebed/1/edit
Issue was fixed in the Internal build 2013.3.1408
New code is:
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
tzoffset = date = date[1];
date = parseInt(date, 10);
tzoffset = tzoffset.substring(1).split(signRegExp)[1];
if (tzoffset) {
date -= (parseInt(tzoffset, 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}
just wondering is there a way to disable all the weekends in the jquery date picker?
Just having a quick look at the documentation, best guess would be to use the beforeShowDay event to disable the days you don't want to be selectable.
use "$("#datepicker").datepicker({ beforeShowDay: $.datepicker.noWeekends });" (change the id selector to match your field).
Do you not want them to be clickable or do you just want to not display them?
The following will hide them:
$("#yourDatePicker").datepicker({ beforeShowDay: $.datepicker.noWeekends });
If you still want to display the weekends, just not let them be selectable, you can use the beforeShowDay. This will check each day to see if it is a Sunday or Saturday, and if it is, returns false so that it will be disabled.
$(document).ready(function () {
$('#myDatePicker').datepicker({
beforeShowDay: disableWeekends
});
function disableWeekends(date) {
var daysToDisable = [0, 6];
var day = date.getDay();
for (i = 0; i < daysToDisable.length; i++) {
if ($.inArray(day, daysToDisable) != -1) {
return [false];
}
}
return [true];
}
});