API Reference Date & Time

Complete reference for date and time APIs across popular programming languages.

Quick API Reference

Common operations across different programming languages.

Get Current Date/Time

// JavaScript new Date() # Python datetime.now() // Java LocalDateTime.now() // PHP new DateTime()

Parse from String

// JavaScript new Date('2024-12-31') # Python datetime.fromisoformat('2024-12-31') // Java LocalDate.parse('2024-12-31') // PHP DateTime::createFromFormat('Y-m-d', '2024-12-31')

Format to String

// JavaScript date.toLocaleDateString('en-GB') # Python date.strftime('%d/%m/%Y') // Java date.format(DateTimeFormatter.ofPattern('dd/MM/yyyy')) // PHP $date->format('d/m/Y')

Add/Subtract Time

// JavaScript date.setDate(date.getDate() + 7) # Python date + timedelta(days=7) // Java date.plusDays(7) // PHP $date->modify('+7 days')

Compare Dates

// JavaScript date1 > date2 # Python date1 > date2 // Java date1.isAfter(date2) // PHP $date1 > $date2
UNIX

Unix Timestamp

// JavaScript Math.floor(date.getTime() / 1000) # Python int(date.timestamp()) // Java date.toEpochSecond() // PHP $date->getTimestamp()

JavaScript Date API

Complete reference for the native JavaScript Date object.

// Date Constructors

// Current date and time
new Date()

// From milliseconds since epoch
new Date(1735689599000)

// From date string
new Date('2024-12-31')
new Date('2024-12-31T23:59:59Z')
new Date('December 31, 2024')

// From date components (month is 0-indexed!)
new Date(2024, 11, 31)              // Dec 31, 2024
new Date(2024, 11, 31, 23, 59, 59)  // With time

// Invalid date
new Date('invalid')                 // Invalid Date object
isNaN(date.getTime())               // Check if valid
// Date Getters

const date = new Date('2024-12-31T23:59:59');

// Local time getters
date.getFullYear()      // 2024
date.getMonth()         // 11 (December, 0-indexed!)
date.getDate()          // 31 (day of month)
date.getDay()           // 2 (Tuesday, 0=Sunday)
date.getHours()         // 23
date.getMinutes()       // 59
date.getSeconds()       // 59
date.getMilliseconds()  // 0

// UTC getters (recommended for storage)
date.getUTCFullYear()
date.getUTCMonth()
date.getUTCDate()
date.getUTCHours()
// ... etc

// Timestamp
date.getTime()          // Milliseconds since epoch
date.valueOf()          // Same as getTime()

// Timezone offset
date.getTimezoneOffset() // Minutes from UTC
// Date Setters (mutate the date object!)

const date = new Date('2024-12-31');

// Local time setters
date.setFullYear(2025)
date.setMonth(0)           // January (0-indexed!)
date.setDate(1)            // Day of month
date.setHours(12)
date.setMinutes(30)
date.setSeconds(45)
date.setMilliseconds(500)

// UTC setters (recommended)
date.setUTCFullYear(2025)
date.setUTCMonth(0)
date.setUTCDate(1)
// ... etc

// Set from timestamp
date.setTime(1735689599000)

// Multiple components at once
date.setFullYear(2025, 0, 1)  // Jan 1, 2025
date.setHours(12, 30, 45)     // 12:30:45

// Note: Setters are mutable!
// Consider using libraries for immutable operations
// Date Formatting Methods

const date = new Date('2024-12-31T23:59:59Z');

// ISO format
date.toISOString()          // '2024-12-31T23:59:59.000Z'
date.toJSON()               // Same as toISOString()

// Locale-aware formatting
date.toLocaleDateString()   // '12/31/2024' (varies by locale)
date.toLocaleTimeString()   // '11:59:59 PM' (varies by locale)
date.toLocaleString()       // Date + time

// With locale parameter
date.toLocaleDateString('en-GB')   // '31/12/2024'
date.toLocaleDateString('en-US')   // '12/31/2024'
date.toLocaleDateString('ja-JP')   // '2024/12/31'

// With options
date.toLocaleDateString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
})  // 'December 31, 2024'

// String representations
date.toString()             // Full string with timezone
date.toDateString()         // 'Tue Dec 31 2024'
date.toTimeString()         // '23:59:59 GMT+0000 (UTC)'
date.toUTCString()          // 'Tue, 31 Dec 2024 23:59:59 GMT'
// Static Date Methods

// Current timestamp
Date.now()                  // Current time in ms since epoch

// Parse date string
Date.parse('2024-12-31')    // Returns timestamp
Date.parse('Dec 31, 2024')  // Also works
Date.parse('invalid')       // Returns NaN

// Create from components
Date.UTC(2024, 11, 31)      // Returns UTC timestamp
Date.UTC(2024, 11, 31, 23, 59, 59)

// Common patterns

// Days between dates
const diff = date2 - date1;
const daysDiff = Math.floor(diff / (1000 * 60 * 60 * 24));

// Add days
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);

// Start of day (midnight)
const startOfDay = new Date(date);
startOfDay.setHours(0, 0, 0, 0);

// End of day
const endOfDay = new Date(date);
endOfDay.setHours(23, 59, 59, 999);

Format String Tokens

Common format tokens used across different languages.

Python strftime

datetime
%Y - Year (2024) %m - Month (01-12) %d - Day (01-31) %H - Hour 24h (00-23) %M - Minute (00-59) %S - Second (00-59) %A - Weekday name %B - Month name

Java DateTimeFormatter

java.time
yyyy - Year (2024) MM - Month (01-12) dd - Day (01-31) HH - Hour 24h (00-23) mm - Minute (00-59) ss - Second (00-59) EEEE - Weekday name MMMM - Month name

PHP date()

DateTime
Y - Year (2024) m - Month (01-12) d - Day (01-31) H - Hour 24h (00-23) i - Minute (00-59) s - Second (00-59) l - Weekday name F - Month name

Moment/Day.js

JavaScript
YYYY - Year (2024) MM - Month (01-12) DD - Day (01-31) HH - Hour 24h (00-23) mm - Minute (00-59) ss - Second (00-59) dddd - Weekday name MMMM - Month name

Intl.DateTimeFormat API

Modern internationalization API for date formatting in JavaScript.

// Intl.DateTimeFormat Examples

const date = new Date('2024-12-31T23:59:59');

// Basic formatting
new Intl.DateTimeFormat('en-US').format(date)
// '12/31/2024'

new Intl.DateTimeFormat('en-GB').format(date)
// '31/12/2024'

// With options
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
};

new Intl.DateTimeFormat('en-US', options).format(date)
// 'Tuesday, December 31, 2024'

// Time zones
new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/New_York',
  dateStyle: 'full',
  timeStyle: 'long'
}).format(date)

// Relative time (Intl.RelativeTimeFormat)
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day')    // 'yesterday'
rtf.format(2, 'week')    // 'in 2 weeks'

// Get parts
const formatter = new Intl.DateTimeFormat('en', {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
});

formatter.formatToParts(date)
// [
//   { type: 'month', value: 'December' },
//   { type: 'literal', value: ' ' },
//   { type: 'day', value: '31' },
//   ...
// ]

API Best Practices

Guidelines for working with date/time APIs.

Always use ISO 8601 for APIs

When sending dates in APIs, always use ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ). It's unambiguous, sortable, and widely supported. Include timezone information with 'Z' for UTC or offset like '+05:30'.

Store dates in UTC

Always store timestamps in UTC in databases. Use getUTC* methods in JavaScript, datetime.utcnow() in Python, etc. Convert to local time only for display purposes.

Beware of JavaScript Date quirks

JavaScript's Date has many gotchas: months are 0-indexed (0=January), getDay() returns 0-6 (0=Sunday), Date is mutable, and timezone handling is limited. Consider using a library for complex operations.

Use native APIs when possible

Modern browsers support Intl.DateTimeFormat for internationalization. Python's datetime, Java's java.time, and Go's time package are excellent built-in options. Only add libraries when you need specific features.

Handle invalid dates gracefully

Always validate dates before processing. In JavaScript, check isNaN(date.getTime()). In Python, catch ValueError. Don't assume user input or external data is valid.

Test across time zones

Test your application in different time zones, especially around DST transitions. Edge cases like "2:30 AM on DST transition day" can cause bugs if not handled properly.

Common Pitfalls

Avoid these common mistakes when working with dates.

JavaScript Month 0-indexing

JavaScript months are 0-indexed (0=January, 11=December) but days are 1-indexed. This inconsistency causes frequent bugs.

// WRONG new Date(2024, 12, 31) // Jan 31, 2025! // CORRECT new Date(2024, 11, 31) // Dec 31, 2024

Date Mutation

JavaScript Date objects are mutable. Setter methods modify the original date, which can cause unexpected behavior.

// WRONG - mutates original const date = new Date(); date.setDate(date.getDate() + 1); // CORRECT - create new date const tomorrow = new Date(date); tomorrow.setDate(tomorrow.getDate() + 1);

Timezone Ambiguity

Date strings without timezone info are interpreted differently. ISO strings without 'Z' are treated as local time.

// AMBIGUOUS new Date('2024-12-31') // Local midnight // EXPLICIT new Date('2024-12-31T00:00:00Z') // UTC

Date Arithmetic

Adding days naively doesn't account for DST. Use proper date libraries or be very careful with manual arithmetic.

// RISKY date.setDate(date.getDate() + 30) // DST? // SAFER - use library luxon.DateTime.now().plus({ days: 30 })

String Comparison

Don't compare date strings directly unless they're in ISO 8601 format (YYYY-MM-DD). Other formats won't sort correctly.

// WRONG '31/12/2024' > '01/01/2025' // true! // CORRECT '2024-12-31' < '2025-01-01' // true

Leap Year Logic

Don't write custom leap year logic. It's more complex than "divisible by 4" due to century rules.

// INCOMPLETE year % 4 === 0 // Wrong for 1900! // USE BUILT-IN new Date(year, 1, 29).getMonth() === 1