Skip to content

isDate

Checks whether a value is of date type.

Basic Usage

typescript
import { isDate } from 'radash'

console.log(isDate(new Date()))           // true
console.log(isDate('2023-01-01'))        // false
console.log(isDate(1234567890))          // false
console.log(isDate(null))                // false

Syntax

typescript
function isDate(value: any): value is Date

Parameters

  • value (any): The value to check

Return Value

Returns a boolean value, true if the value is a Date object, false otherwise.

Examples

Checking Date Objects

typescript
import { isDate } from 'radash'

console.log(isDate(new Date()))                    // true
console.log(isDate(new Date('2023-01-01')))       // true
console.log(isDate(new Date(1234567890)))         // true
console.log(isDate(new Date('invalid')))          // true (still a Date object, just invalid)

Checking Non-Date Values

typescript
import { isDate } from 'radash'

console.log(isDate('2023-01-01'))                 // false
console.log(isDate('2023/01/01'))                 // false
console.log(isDate('2023.01.01'))                 // false
console.log(isDate('January 1, 2023'))            // false

Checking Numbers

typescript
import { isDate } from 'radash'

console.log(isDate(1234567890))                   // false
console.log(isDate(0))                            // false
console.log(isDate(-1234567890))                  // false
console.log(isDate(3.14))                         // false

Checking Other Types

typescript
import { isDate } from 'radash'

console.log(isDate(null))                         // false
console.log(isDate(undefined))                    // false
console.log(isDate(true))                         // false
console.log(isDate(false))                        // false
console.log(isDate([]))                           // false
console.log(isDate({}))                           // false
console.log(isDate(() => {}))                     // false
console.log(isDate(/regex/))                      // false

Using in Functions

typescript
import { isDate } from 'radash'

function formatDate(value: any): string {
  if (isDate(value)) {
    return value.toISOString()
  }
  return 'Invalid date'
}

console.log(formatDate(new Date()))               // '2023-01-01T00:00:00.000Z'
console.log(formatDate('2023-01-01'))            // 'Invalid date'
console.log(formatDate(1234567890))              // 'Invalid date'

Using in Array Filtering

typescript
import { isDate } from 'radash'

const mixedArray = [
  new Date(),
  '2023-01-01',
  1234567890,
  new Date('2023-01-01'),
  'hello',
  null
]

const dateArray = mixedArray.filter(isDate)
console.log(dateArray) // [Date, Date] (only contains Date objects)

Type Guards

typescript
import { isDate } from 'radash'

function processValue(value: unknown) {
  if (isDate(value)) {
    // TypeScript knows value is Date type here
    console.log(value.getFullYear()) // Can safely call Date methods
    console.log(value.toISOString())
  } else {
    console.log('Not a date:', value)
  }
}

processValue(new Date())     // Outputs year and ISO string
processValue('2023-01-01')  // 'Not a date: 2023-01-01'

Validating Form Input

typescript
import { isDate } from 'radash'

function validateDateInput(input: any): boolean {
  if (isDate(input)) {
    return !isNaN(input.getTime()) // Check if it's a valid date
  }
  return false
}

console.log(validateDateInput(new Date()))                    // true
console.log(validateDateInput(new Date('invalid')))          // false
console.log(validateDateInput('2023-01-01'))                 // false
console.log(validateDateInput(1234567890))                   // false

Handling API Responses

typescript
import { isDate } from 'radash'

interface ApiResponse {
  id: number
  name: string
  createdAt: any
  updatedAt: any
}

function processApiResponse(response: ApiResponse) {
  const processed = {
    ...response,
    createdAt: isDate(response.createdAt) ? response.createdAt : new Date(response.createdAt),
    updatedAt: isDate(response.updatedAt) ? response.updatedAt : new Date(response.updatedAt)
  }
  
  return processed
}

const response: ApiResponse = {
  id: 1,
  name: 'Test',
  createdAt: new Date(),
  updatedAt: '2023-01-01T00:00:00.000Z'
}

const processed = processApiResponse(response)
console.log(isDate(processed.createdAt)) // true
console.log(isDate(processed.updatedAt)) // true

Checking Invalid Dates

typescript
import { isDate } from 'radash'

// These are still Date objects, but represent invalid dates
const invalidDates = [
  new Date('invalid'),
  new Date(''),
  new Date('not a date'),
  new Date(NaN)
]

invalidDates.forEach(date => {
  console.log(isDate(date))           // true (all are Date objects)
  console.log(isNaN(date.getTime()))  // true (but all are invalid dates)
})

Notes

  1. Type Check Only: isDate only checks if the value is a Date object, not if the date is valid
  2. Invalid Dates: Even if a Date object represents an invalid date, isDate will still return true
  3. Type Guards: In TypeScript, this function can be used as a type guard
  4. Performance: The check operation is very fast, just a simple type check
  5. Cross-platform: Works correctly in all JavaScript environments

Differences from Other Methods

  • instanceof Date: Same functionality, but isDate is more concise
  • Object.prototype.toString.call(value) === '[object Date]': More complex but more reliable
  • isDate(): Concise API provided by radash
  • typeof value === 'object' && value !== null && 'getTime' in value: Check Date methods

Practical Application Scenarios

  1. Form Validation: Check if user input is a valid date
  2. API Processing: Validate date fields in API responses
  3. Data Transformation: Check date types during data transformation
  4. Type Guards: Provide type safety in TypeScript
  5. Error Handling: Perform type checks in date processing functions

Released under the MIT License.