Skip to content

Date Range Component

A flexible and comprehensive Vue 3 component for selecting date ranges with support for both Gregorian (AD) and Nepali (BS) calendars. Features preset date types, custom date selection, calendar system toggle, and automatic search functionality.


Props

PropTypeDefaultDescription
modelValueDateObject{ startDate: '', endDate: '', dateType: 'today', isBS: false }The date range object containing all date selection state
searchOnLoadbooleanfalseIf true, automatically triggers search event when component mounts

DateObject Interface

typescript
interface DateObject {
  startDate: string;  // AD format (YYYY-MM-DD) - always stored in AD regardless of display
  endDate: string;    // AD format (YYYY-MM-DD) - always stored in AD regardless of display
  dateType: string;   // ID of the selected date type preset
  isBS: boolean;      // Whether to display dates in Nepali calendar (BS)
}

Emits

EventParametersDescription
update:modelValueDateObjectEmitted whenever any part of the date object changes
searchDateObjectEmitted when the Search button is clicked or on component load if searchOnLoad is true

Date Type Presets

The component includes the following predefined date ranges:

Date Type IDDisplay NameDescription
year_to_dateYear to dateFrom fiscal year start to today
quarter_to_dateQuarter to dateFrom current quarter start to today
month_to_dateMonth to dateFrom current month start to today
week_to_dateWeek to dateFrom current week start to today
todayTodayCurrent day only
last_30_daysLast 30 days30 days ago to today
last_90_daysLast 90 days90 days ago to today
first_quarterFirst quarter (Q1)Complete first fiscal quarter
second_quarterSecond quarter (Q2)Complete second fiscal quarter
third_quarterThird quarter (Q3)Complete third fiscal quarter
fourth_quarterFourth quarter (Q4)Complete fourth fiscal quarter
customCustomAutomatically set when user selects custom dates

Features

Dual Calendar Support

  • Gregorian Calendar (AD): Standard international calendar system
  • Nepali Calendar (BS): Bikram Sambat calendar system with automatic conversion
  • Seamless Toggle: Switch between calendar systems while preserving date logic
  • Automatic Conversion: Internal date storage always in AD format with display conversion

Preset Date Ranges

  • Fiscal Year Support: Nepali fiscal year quarters and year-to-date calculations
  • Common Ranges: Today, last 30/90 days, month/week/quarter to date
  • Smart Calculations: All presets calculated based on current Nepali date
  • Automatic Updates: Dates automatically update when preset selection changes

Custom Date Selection

  • Manual Date Picking: Select any start and end date using date pickers
  • Auto-Detection: Automatically switches to "Custom" when manual dates are selected
  • Calendar-Specific Pickers: Uses appropriate date picker based on BS/AD toggle
  • Real-time Updates: Immediate feedback when dates are changed

Intelligent State Management

  • Synchronized State: Internal and external state always in sync
  • Format Conversion: Automatic conversion between BS and AD formats
  • Validation: Ensures date consistency across calendar systems
  • Change Detection: Watches for external prop changes and updates internal state

Search Functionality

  • Manual Search: Explicit search button for controlled data fetching
  • Auto-search on Load: Optional automatic search when component initializes
  • Event Emission: Emits complete date object with search event
  • State Preservation: Maintains current date selection during search operations

Usage Examples

Basic Usage

vue
<script setup>
import { ref } from 'vue'

const dateRange = ref({
  startDate: '',
  endDate: '',
  dateType: 'today',
  isBS: false
})

function handleSearch(dateObject) {
  console.log('Searching with dates:', dateObject)
  // Make API call with date range
  fetchReportData(dateObject.startDate, dateObject.endDate)
}

function fetchReportData(startDate, endDate) {
  // Your API call logic here
  console.log(`Fetching data from ${startDate} to ${endDate}`)
}
</script>

<template>
  <DateRange
    v-model="dateRange"
    @search="handleSearch"
  />
</template>

With Auto-search on Load

vue
<script setup>
import { ref } from 'vue'

const reportDateRange = ref({
  startDate: '',
  endDate: '',
  dateType: 'last_30_days',
  isBS: true  // Start with Nepali calendar
})

function loadReport(dateObject) {
  console.log('Auto-loading report:', dateObject)
  // Automatically fetch data when component loads
}
</script>

<template>
  <DateRange
    v-model="reportDateRange"
    :search-on-load="true"
    @search="loadReport"
  />
</template>

Reactive Date Range with Watch

vue
<script setup>
import { ref, watch } from 'vue'

const dateSelection = ref({
  startDate: '',
  endDate: '',
  dateType: 'quarter_to_date',
  isBS: false
})

// Watch for changes in date selection
watch(dateSelection, (newValue) => {
  console.log('Date range updated:', newValue)
  updateChartData(newValue)
}, { deep: true })

function updateChartData(dateObject) {
  // Update charts or other UI elements based on date changes
  console.log(`Chart data updating for ${dateObject.dateType}`)
}

function performSearch(dateObject) {
  console.log('Performing search:', dateObject)
}
</script>

<template>
  <DateRange
    v-model="dateSelection"
    @search="performSearch"
  />
  
  <div class="mt-4">
    <p>Current Selection: {{ dateSelection.dateType }}</p>
    <p>Date Range: {{ dateSelection.startDate }} to {{ dateSelection.endDate }}</p>
    <p>Calendar: {{ dateSelection.isBS ? 'Nepali (BS)' : 'Gregorian (AD)' }}</p>
  </div>
</template>

Advanced Integration with API

vue
<script setup>
import { ref, computed } from 'vue'
import axios from 'axios'

const dateFilter = ref({
  startDate: '',
  endDate: '',
  dateType: 'month_to_date',
  isBS: false
})

const isLoading = ref(false)
const reportData = ref([])

// Computed property to format dates for API
const apiDateRange = computed(() => ({
  start_date: dateFilter.value.startDate,
  end_date: dateFilter.value.endDate,
  calendar_type: dateFilter.value.isBS ? 'bs' : 'ad'
}))

async function fetchReport(dateObject) {
  isLoading.value = true
  try {
    const response = await axios.post('/api/reports', {
      ...apiDateRange.value,
      report_type: 'financial'
    })
    reportData.value = response.data
    console.log('Report loaded successfully')
  } catch (error) {
    console.error('Failed to load report:', error)
  } finally {
    isLoading.value = false
  }
}

function resetToToday() {
  dateFilter.value = {
    startDate: '',
    endDate: '',
    dateType: 'today',
    isBS: false
  }
}
</script>

<template>
  <div class="space-y-4">
    <DateRange
      v-model="dateFilter"
      :search-on-load="true"
      @search="fetchReport"
    />
    
    <div class="flex gap-2">
      <button 
        @click="resetToToday" 
        class="btn btn-outline"
      >
        Reset to Today
      </button>
      <button 
        :disabled="isLoading"
        @click="fetchReport(dateFilter)"
        class="btn btn-primary"
      >
        {{ isLoading ? 'Loading...' : 'Refresh Report' }}
      </button>
    </div>
    
    <div v-if="reportData.length" class="bg-gray-50 p-4 rounded">
      <h3>Report Data ({{ reportData.length }} records)</h3>
      <!-- Display your report data here -->
    </div>
  </div>
</template>

Component Behavior Details

Date Initialization

  • Default Values: If no start/end dates provided, defaults to today's date
  • Calendar Format: Internal storage always in AD format, display format based on isBS setting
  • Preset Selection: Defaults to "today" if no date type specified
  • Auto-search: Triggers search on mount if searchOnLoad is enabled

Calendar System Toggle

  • Format Conversion: Automatically converts displayed dates between BS and AD
  • Data Integrity: Internal date storage remains in AD format for consistency
  • Visual Update: Date pickers update to show appropriate calendar system
  • State Synchronization: Toggle state syncs with parent component through v-model

Date Range Calculations

  • Fiscal Year Logic: Uses Nepali fiscal year system for year-to-date and quarterly calculations
  • Smart Presets: All preset calculations use current Nepali date as reference
  • Real-time Updates: Preset dates automatically update based on current date
  • Custom Override: Manual date selection automatically switches to "custom" type

State Management

  • Two-way Binding: Full v-model support with automatic state synchronization
  • Change Detection: Watches for external prop changes and updates internal state
  • Event Emission: Emits updates for every state change and search action
  • Validation: Ensures date consistency and proper format conversion

Dependencies

  • vue-datepicker-next: Gregorian (AD) date picker component
  • nepali-datepicker-vue: Nepali (BS) date picker component
  • nepali-date-library: Date conversion utilities (ADtoBS, BStoAD, NepaliDate)
  • vue-multiselect: Date type preset selector
  • Toggle Component: Custom toggle component for BS/AD switch

Internal Implementation Notes

Date Storage Strategy

  • External API always receives dates in AD format for consistency
  • Internal display dates are converted based on isBS setting
  • All date calculations use NepaliDate library for accuracy

Watcher System

  • Comprehensive watchers for prop changes and internal state sync
  • Prevents infinite loops during date conversion processes
  • Handles external prop updates gracefully

Custom Date Detection

  • Any manual date selection automatically sets dateType to "custom"
  • Preserves user intent while maintaining preset system functionality
  • Allows seamless transition between preset and custom selections

Best Practices

Usage Recommendations

  • Always use v-model for two-way data binding
  • Handle the search event for data fetching operations
  • Consider using searchOnLoad for immediate data loading scenarios
  • Store date filters in reactive refs for optimal performance

Date Handling

  • External APIs should expect AD format dates regardless of display calendar
  • Use the isBS flag to determine user's preferred calendar display
  • Leverage preset date types for common date range scenarios
  • Custom date ranges are ideal for specific reporting needs

Performance Considerations

  • Watch the date object with deep: true if you need to react to all changes
  • Debounce search operations if automatic searching is implemented
  • Cache frequently used date calculations for better performance

Screenshot

date-range image


Common Use Cases

  • Report Filtering: Filter reports by date ranges with preset options
  • Data Analytics: Select time periods for analytics dashboards
  • Financial Reports: Use fiscal year quarters for financial reporting
  • Event Filtering: Filter events by date ranges in calendar applications
  • Audit Logs: Select date ranges for audit log viewing
  • Performance Tracking: Track performance metrics over specific periods