Home

Awesome

Date Range Picker for Blazor

Nuget (with prereleases)

https://github.com/jdtcn/BlazorDateRangePicker

Live Demo

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.

Get Started

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">

Use the component:

@using BlazorDateRangePicker

<DateRangePicker/>

Gives you:

<input type="text"/>

Tag attributes will be passed to input field:

@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..."/>

Setting properties:

@using BlazorDateRangePicker

<DateRangePicker MinDate="DateTimeOffset.Now.AddYears(-10)" MaxDate="DateTimeOffset.Now" />

Two-way data binding:

@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);
}

Handle selection event:

@using BlazorDateRangePicker

<DateRangePicker OnRangeSelect="OnRangeSelect" />

@code {
    public void OnRangeSelect(DateRange range)
    {
        //Use range.Start and range.End here
    }
}

More complex usage:

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>&nbsp;
            <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.

One configuration for all pickers

#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" />

Properties

NameTypeDefaultValueDescription
StartDateDateTimeOffset?nullThe beginning date of the initially selected date range.
EndDateDateTimeOffset?nullThe end date of the initially selected date range.
MinDateDateTimeOffset?nullThe earliest date a user may select.
MaxDateDateTimeOffset?nullThe latest date a user may select.
MinSpanTimeSpan?nullThe minimum span between the selected start and end dates.
MaxSpanTimeSpan?nullThe maximum span between the selected start and end dates.
ShowDropdownsbooltrueShow year and month select boxes above calendars to jump to a specific month and year.
ShowWeekNumbersboolfalseShow localized week numbers at the start of each week on the calendars.
ShowISOWeekNumbersboolfalseShow ISO week numbers at the start of each week on the calendars.
RangesDictionary<string, DateRange>nullSet predefined date ranges the user can select from. Each key is the label for the range.
ShowCustomRangeLabelbooltrueDisplays "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.
AlwaysShowCalendarsboolfalseNormally, 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.
OpensSideType enum: Left/Right/CenterRightWhether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to.
DropsDropsType enum: Down/UpDownWhether the picker appears below (default) or above the HTML element it's attached to.
ButtonClassesstringbtn btn-smCSS class names that will be added to both the apply and cancel buttons.
ApplyButtonClassesstringbtn-primaryCSS class names that will be added only to the apply button.
CancelButtonClassesstringbtn-defaultCSS class names that will be added only to the cancel button.
CultureCultureInfoCultureInfo.CurrentCultureAllows you to provide localized strings for buttons and labels, customize the date format, and change the first day of week for the calendars.
SingleDatePickerboolfalseShow 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.
AutoApplyboolfalseHide the apply and cancel buttons, and automatically apply a new date range as soon as two dates are clicked.
LinkedCalendarsboolfalseWhen 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.
DaysEnabledFunctionFunc<DateTimeOffset, bool>_ => trueA 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.
DaysEnabledFunctionAsyncFunc< DateTimeOffset, Task< bool>>_ => trueSame as DaysEnabledFunction but with async support.
CustomDateFunctionFunc<DateTimeOffset, object>_ => trueA 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<string>, Task<bool>
CustomDateClassstringstring.EmptyString of CSS class name to apply to that custom date's calendar cell.
ApplyLabelstring"Apply"Apply button text.
CancelLabelstring"Cancel"Cancel button text.
CustomRangeLabelstring"Custom range"Custom range label at the end of the list of predefined ranges.
DateFormatstringCultureInfo.DateTimeFormat.ShortDatePatternEnforces the desired format for formatting the date, ignoring the settings of the current CultureInfo.
ConfigstringnullName of the named configuration to use with this picker instance.
ShowOnlyOneCalendarboolfalseShow only one calendar in the picker instead of two calendars.
CloseOnOutsideClickbooltrueWhether the picker should close on outside click.
AutoAdjustCalendarsbooltrueWhether the picker should pick the months based on selected range.
PickerTemplateRenderFragment<DateRangePicker>nullCustom input field template
ButtonsTemplateRenderFragment<DateRangePicker>nullCustom picker buttons template
DayTemplateRenderFragment<CalendarItem>nullCustom day cell template
InlineboolfalseInline mode if true.
ResetOnClearbooltrueWhether the picker should set dates to null when the user clears the input.
TimePickerboolfalseAdds select boxes to choose times in addition to dates.
TimePicker24HourbooltrueUse 24-hour instead of 12-hour times, removing the AM/PM selection.
TimePickerIncrementint1Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30).
TimePickerSecondsboolfalseShow seconds in the timePicker.
InitialStartTimeTimeSpanTimeSpan.ZeroInitial start time value to show in the picker before any date selected
InitialEndTimeTimeSpanTimeSpan.FromDays(1).AddTicks(-1)Initial end time value to show in the picker before any date selected
TimeEnabledFunctionFunc<DateTimeOffset?, Task<TimeSettings>>nullReturns time available for selection.

Events

NameTypeDescription
OnRangeSelectDateRangeTriggered when the apply button is clicked, or when a predefined range is clicked.
OnOpenedvoidAn event that is invoked when the DatePicker is opened.
OnClosedvoidAn event that is invoked when the DatePicker is closed.
OnCancelboolAn event that is invoked when user cancels the selection (true if by pressing "Cancel" button, false if by backdrop click).
OnResetvoidAn event that is invoked when the DatePicker is cleared.
OnMonthChangedvoidAn event that is invoked when left or right calendar's month changed.
OnMonthChangedAsyncTaskAn 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.
OnSelectionStartDateTimeOffsetAn event that is invoked when StartDate is selected
OnSelectionEndDateTimeOffsetAn event that is invoked when EndDate is selected but before "Apply" button is clicked

Methods

NameDescription
OpenShow picker popup.
CloseClose picker popup.
ToggleToggle picker popup state.
ResetRest picker.
virtual InvokeClickOutsideA JSInvocable callback to handle outside click. When inherited can be overridden to modify outside click closing behavior.

Types

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)).

Changelog

5.3.0

  1. Fixed the issue with TimePicker24Hour not working on left calendar (#104)

5.2.0

  1. Fixed the issue with caching of clickAndPositionHandler.js (#96)

5.1.0

  1. Fixed the issue with clickAndPositionHandler.js (#96, #97)

5.0.0

  1. Removed inline style usage to make CSP work (#95)
  2. Fixed awaiting change handlers before closing (#91)
  3. 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)
  4. Removed NET Core 3.1 and NET 5 support

4.5.0

  1. Added net 8 support
  2. Fixed TimePicker24Hour has wrong value issue (#90)
  3. Added the ability to display two calendars in single date select mode (#87)

4.4.0

  1. Made it possible to change culture on the fly (#89)
  2. Added net 8 rc1 support

4.3.0

  1. Updated to net 7

4.2.0

  1. Fixed same date selection issue when TimePicker is enabled
  2. Fixed predefined date ranges with time
  3. Made ChosenLabel property public
  4. Added net7 support

4.1.0

  1. Fixed months adjustment issue (#69)
  2. Fixed problems with dates 01/01/0001 and 31/12/9999

4.0.0

  1. Updated to NET 6
  2. Fixed issue with handling of DateTime.MinValue and DateTime.MaxValue dates (#65)

3.6.0

  1. Disable AutoApply when TimePicker is enabled (#57)

3.5.0

  1. Added time picker
  2. Added Prerender property (ability to render DOM only after click on the input) (#52)

3.4.0

  1. Added net 6 support

3.3.0

  1. Fixed issue with month & year selection (#45)

3.2.0

  1. Added ability to reset the picker by clearing the picker input (#42)
  2. Added ResetOnClear property
  3. Added OnReset event
  4. Added Reset method

2.13.0

  1. Added ability to change input field id attribute (#41)

2.12.0

  1. Added new OnSelectionEnd event
  2. Added new demo example which demonstrates how to override day click handlers
  3. Exposed some internals that might be useful for picker customization

2.11.0

  1. Fix month/year select box issue (#34, #35)

2.10.0

  1. Add DayTemplate property to customize picker day cell

  2. Demo applications refactored and updated with new examples

2.9.0

  1. Fix issue with two-way dates binding (#32)
  2. Fix issue with date range label selection
  3. Fix issue with single date selection mode
  4. OnSelectionStart event now returns selected start date

2.8.0

  1. Add OnSelectionStart event (#29)
  2. Add MinSpan property (#29)

2.7.0

  1. Breaking change! CustomDateFunction changed from Func<DateTimeOffset, bool> to Func<DateTimeOffset, object> so that it can return string, bool, Task<string>, Task<bool>.
  2. OnMonthChangedAsync event added to support data loading indication.
  3. Fixed issue with compilerconfig.json file (#27).

2.6.0

  1. Add inline mode (see Inline property, and last example in demo application) (#20)

2.5.0

  1. Add OnMonthChanged event (#19)

2.4.0

  1. Add ButtonsTemplate property to make custom picker buttons possible (#17)

2.3.0

  1. Fix an issue with month selection in calendars (#14).
  2. Add AutoAdjustCalendars property.
  3. Expose LeftCalendar and RightCalendar DateRangePicker options (ability to select the months manually).
  4. Fix an issue with FirstDayOfWeek property when the first day is not sunday or monday.

2.2.0

  1. Fixed performance issue with js outside click handler.

2.1.0

  1. OnCancel event added.

2.0.0

  1. Updated to support .NET Core 3.1.0 projects
  2. 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

License

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.