Date Range Picker for Blazor
This date range picker component is a port of js DateRangePicker, rewritten using C# as a Razor Component. It creates a dropdown menu from which a user can select a range of dates.
There is no dependency with jquery, moment, or bootstrap
Features include limiting the selectable date range, localizable strings and date formats, a single date picker mode, and predefined date ranges.
JS Interop is used for popup positioning and outside click handling. With future releases of ASP.NET Core Blazor it will be possible without js.
Download library from NuGet in the NuGet Package Manager, or by executing the following command in the Package Manager Console:
Install-Package BlazorDateRangePicker
The component uses css and js isolation, you don't need to add anything to your _Host.cshtml or index.html, just make sure the isolated styles are connected:
<link href="{ASSEMBLY NAME}.styles.css" rel="stylesheet">
@using BlazorDateRangePicker
<DateRangePicker/>
Gives you:
<input type="text"/>
@using BlazorDateRangePicker
<DateRangePicker class="form-control form-control-sm" placeholder="Select dates..." />
Gives you:
<input type="text" class="form-control form-control-sm" placeholder="Select dates..."/>
@using BlazorDateRangePicker
<DateRangePicker MinDate="DateTimeOffset.Now.AddYears(-10)" MaxDate="DateTimeOffset.Now" />
@using BlazorDateRangePicker
<DateRangePicker @bind-StartDate="StartDate" @bind-EndDate="EndDate" />
@code {
DateTimeOffset? StartDate { get; set; } = DateTime.Today.AddMonths(-1);
DateTimeOffset? EndDate { get; set; } = DateTime.Today.AddDays(1).AddTicks(-1);
}
@using BlazorDateRangePicker
<DateRangePicker OnRangeSelect="OnRangeSelect" />
@code {
public void OnRangeSelect(DateRange range)
{
//Use range.Start and range.End here
}
}
Using custom markup for picker.
@using BlazorDateRangePicker
<DateRangePicker Culture="@(System.Globalization.CultureInfo.GetCultureInfo("en-US"))">
<PickerTemplate>
<div id="@context.Id" @onclick="context.Toggle" style="background: #fff; cursor: pointer; padding: 5px 10px; width: 250px; border: 1px solid #ccc;">
<i class="oi oi-calendar"></i>
<span>@context.FormattedRange @(string.IsNullOrEmpty(context.FormattedRange) ? "Choose dates..." : "")</span>
<i class="oi oi-chevron-bottom float-right"></i>
</div>
</PickerTemplate>
</DateRangePicker>
Set id="@context.Id" for outside click handling to root element.
Custom buttons:
<DateRangePicker @bind-StartDate="StartDate" @bind-EndDate="EndDate">
<ButtonsTemplate>
<button class="cancelBtn btn btn-sm btn-default"
@onclick="@context.ClickCancel" type="button">Cancel</button>
<button class="cancelBtn btn btn-sm btn-default"
@onclick="@(e => ResetClick(e, context))" type="button">Reset</button>
<button class="applyBtn btn btn-sm btn-primary" @onclick="@context.ClickApply"
disabled="@(context.TStartDate == null || context.TEndDate == null)"
type="button">Apply</button>
</ButtonsTemplate>
</DateRangePicker>
@code {
DateTimeOffset? StartDate { get; set; }
DateTimeOffset? EndDate { get; set; }
void ResetClick(MouseEventArgs e, DateRangePicker picker)
{
StartDate = null;
EndDate = null;
// Close the picker
picker.Close();
// Fire OnRangeSelectEvent
picker.OnRangeSelect.InvokeAsync(new DateRange());
}
}
Use Picker.TStartDate and Picker.TEndDate properties to get current picker state before a user clicks the 'apply' button.
#Startup.cs
using BlazorDateRangePicker;
//ConfigureServices
services.AddDateRangePicker(config =>
{
config.Attributes = new Dictionary<string, object>
{
{ "class", "form-control form-control-sm" }
};
});
It's possible to create multiple named config instances and bind it to picker with "Config" property.
services.AddDateRangePicker(config => ..., configName: "CustomConfig");
<DateRangePicker Config="CustomConfig" />
Name | Type | DefaultValue | Description |
---|---|---|---|
StartDate | DateTimeOffset? | null | The beginning date of the initially selected date range. |
EndDate | DateTimeOffset? | null | The end date of the initially selected date range. |
MinDate | DateTimeOffset? | null | The earliest date a user may select. |
MaxDate | DateTimeOffset? | null | The latest date a user may select. |
MinSpan | TimeSpan? | null | The minimum span between the selected start and end dates. |
MaxSpan | TimeSpan? | null | The maximum span between the selected start and end dates. |
ShowDropdowns | bool | true | Show year and month select boxes above calendars to jump to a specific month and year. |
ShowWeekNumbers | bool | false | Show localized week numbers at the start of each week on the calendars. |
ShowISOWeekNumbers | bool | false | Show ISO week numbers at the start of each week on the calendars. |
Ranges | Dictionary<string, DateRange> | null | Set predefined date ranges the user can select from. Each key is the label for the range. |
ShowCustomRangeLabel | bool | true | Displays "Custom Range" at the end of the list of predefined ranges, when the ranges option is used. This option will be highlighted whenever the current date range selection does not match one of the predefined ranges. Clicking it will display the calendars to select a new range. |
AlwaysShowCalendars | bool | false | Normally, if you use the ranges option to specify pre-defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range". When this option is set to true, the calendars for choosing a custom date range are always shown instead. |
Opens | SideType enum: Left/Right/Center | Right | Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to. |
Drops | DropsType enum: Down/Up | Down | Whether the picker appears below (default) or above the HTML element it's attached to. |
ButtonClasses | string | btn btn-sm | CSS class names that will be added to both the apply and cancel buttons. |
ApplyButtonClasses | string | btn-primary | CSS class names that will be added only to the apply button. |
CancelButtonClasses | string | btn-default | CSS class names that will be added only to the cancel button. |
Culture | CultureInfo | CultureInfo.CurrentCulture | Allows you to provide localized strings for buttons and labels, customize the date format, and change the first day of week for the calendars. |
SingleDatePicker | bool | false | Show only a single calendar to choose one date, instead of a range picker with two calendars. The start and end dates provided to your callback will be the same single date chosen. |
AutoApply | bool | false | Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates are clicked. |
LinkedCalendars | bool | false | When enabled, the two calendars displayed will always be for two sequential months (i.e. January and February), and both will be advanced when clicking the left or right arrows above the calendars. When disabled, the two calendars can be individually advanced and display any month/year. |
DaysEnabledFunction | Func<DateTimeOffset, bool> | _ => true | A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. |
DaysEnabledFunctionAsync | Func< DateTimeOffset, Task< bool>> | _ => true | Same as DaysEnabledFunction but with async support. |
CustomDateFunction | Func<DateTimeOffset, object> | _ => true | A function to which each date from the calendars is passed before they are displayed, may return a bool value indicates whether the string will be added to the cell, or a string with CSS class name to add to that date's calendar cell. May return string, bool, Task, Task |
CustomDateClass | string | string.Empty | String of CSS class name to apply to that custom date's calendar cell. |
ApplyLabel | string | "Apply" | Apply button text. |
CancelLabel | string | "Cancel" | Cancel button text. |
CustomRangeLabel | string | "Custom range" | Custom range label at the end of the list of predefined ranges. |
DateFormat | string | CultureInfo.DateTimeFormat.ShortDatePattern | Enforces the desired format for formatting the date, ignoring the settings of the current CultureInfo. |
Config | string | null | Name of the named configuration to use with this picker instance. |
ShowOnlyOneCalendar | bool | false | Show only one calendar in the picker instead of two calendars. |
CloseOnOutsideClick | bool | true | Whether the picker should close on outside click. |
AutoAdjustCalendars | bool | true | Whether the picker should pick the months based on selected range. |
PickerTemplate | RenderFragment | null | Custom input field template |
ButtonsTemplate | RenderFragment | null | Custom picker buttons template |
DayTemplate | RenderFragment | null | Custom day cell template |
Inline | bool | false | Inline mode if true. |
ResetOnClear | bool | true | Whether the picker should set dates to null when the user clears the input. |
TimePicker | bool | false | Adds select boxes to choose times in addition to dates. |
TimePicker24Hour | bool | true | Use 24-hour instead of 12-hour times, removing the AM/PM selection. |
TimePickerIncrement | int | 1 | Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30). |
TimePickerSeconds | bool | false | Show seconds in the timePicker. |
InitialStartTime | TimeSpan | TimeSpan.Zero | Initial start time value to show in the picker before any date selected |
InitialEndTime | TimeSpan | TimeSpan.FromDays(1).AddTicks(-1) | Initial end time value to show in the picker before any date selected |
TimeEnabledFunction | Func<DateTimeOffset?, Task> | null | Returns time available for selection. |
Name | Type | Description |
---|---|---|
OnRangeSelect | DateRange | Triggered when the apply button is clicked, or when a predefined range is clicked. |
OnOpened | void | An event that is invoked when the DatePicker is opened. |
OnClosed | void | An event that is invoked when the DatePicker is closed. |
OnCancel | bool | An event that is invoked when user cancels the selection (true if by pressing "Cancel" button, false if by backdrop click). |
OnReset | void | An event that is invoked when the DatePicker is cleared. |
OnMonthChanged | void | An event that is invoked when left or right calendar's month changed. |
OnMonthChangedAsync | Task | An event that is invoked when left or right calendar's month changed and supports CancellationToken. Use this event handler to prepare the data for CustomDateFunction. |
OnSelectionStart | DateTimeOffset | An event that is invoked when StartDate is selected |
OnSelectionEnd | DateTimeOffset | An event that is invoked when EndDate is selected but before "Apply" button is clicked |
Name | Description |
---|---|
Open | Show picker popup. |
Close | Close picker popup. |
Toggle | Toggle picker popup state. |
Reset | Rest picker. |
virtual InvokeClickOutside | A JSInvocable callback to handle outside click. When inherited can be overridden to modify outside click closing behavior. |
DateRange:
public class DateRange
{
public DateTimeOffset Start { get; set; }
public DateTimeOffset End { get; set; }
}
Note: DateRange Start and End is in local timezone.
The Start property is the start of a selected day (dateTime.Date).
The End property is the end of a selected day (dateTime.Date.AddDays(1).AddTicks(-1)).
- Fixed the issue with TimePicker24Hour not working on left calendar (#104)
- Fixed the issue with caching of clickAndPositionHandler.js (#96)
- Fixed the issue with clickAndPositionHandler.js (#96, #97)
- Removed inline style usage to make CSP work (#95)
- Fixed awaiting change handlers before closing (#91)
- Switched the component to use css and js isolation, you don't need to add js and css links to your _Host.cshtml manually anymore (#66)
- Removed NET Core 3.1 and NET 5 support
- Added net 8 support
- Fixed TimePicker24Hour has wrong value issue (#90)
- Added the ability to display two calendars in single date select mode (#87)
- Made it possible to change culture on the fly (#89)
- Added net 8 rc1 support
- Updated to net 7
- Fixed same date selection issue when TimePicker is enabled
- Fixed predefined date ranges with time
- Made
ChosenLabel
property public - Added net7 support
- Fixed months adjustment issue (#69)
- Fixed problems with dates 01/01/0001 and 31/12/9999
- Updated to NET 6
- Fixed issue with handling of DateTime.MinValue and DateTime.MaxValue dates (#65)
- Disable AutoApply when TimePicker is enabled (#57)
- Added time picker
- Added Prerender property (ability to render DOM only after click on the input) (#52)
- Added net 6 support
- Fixed issue with month & year selection (#45)
- Added ability to reset the picker by clearing the picker input (#42)
- Added
ResetOnClear
property - Added
OnReset
event - Added
Reset
method
- Added ability to change input field
id
attribute (#41)
- Added new
OnSelectionEnd
event - Added new demo example which demonstrates how to override day click handlers
- Exposed some internals that might be useful for picker customization
- Fix month/year select box issue (#34, #35)
-
Add
DayTemplate
property to customize picker day cell -
Demo applications refactored and updated with new examples
- Fix issue with two-way dates binding (#32)
- Fix issue with date range label selection
- Fix issue with single date selection mode
OnSelectionStart
event now returns selected start date
- Add OnSelectionStart event (#29)
- Add MinSpan property (#29)
- Breaking change! CustomDateFunction changed from Func<DateTimeOffset, bool> to Func<DateTimeOffset, object> so that it can return string, bool, Task, Task.
- OnMonthChangedAsync event added to support data loading indication.
- Fixed issue with compilerconfig.json file (#27).
- Add inline mode (see
Inline
property, and last example in demo application) (#20)
- Add
OnMonthChanged
event (#19)
- Add
ButtonsTemplate
property to make custom picker buttons possible (#17)
- Fix an issue with month selection in calendars (#14).
- Add AutoAdjustCalendars property.
- Expose LeftCalendar and RightCalendar DateRangePicker options (ability to select the months manually).
- Fix an issue with FirstDayOfWeek property when the first day is not sunday or monday.
- Fixed performance issue with js outside click handler.
- OnCancel event added.
- Updated to support .NET Core 3.1.0 projects
- Now in Blazor WebAssembly we need to add library static assets manually
In .NET Core 3.0.0 projects you should stay on 1.*.* version
The MIT License (MIT)
Copyright (c) 2019-2024 Sergey Zaikin
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.