JavaScript Date & Libraries

Generate date code for vanilla JavaScript, dayjs, and date-fns. Pick a library and operation — get copy-ready code with imports.

Select a library and operation above

How to Use This Tool

Select a JavaScript library from the tabs — vanilla JS (no dependencies), dayjs (lightweight Moment.js replacement), or date-fns (tree-shakeable utility functions). Then pick an operation. The tool generates practical code with the correct imports, realistic examples, and comments explaining the gotchas you're likely to hit.

Every code block includes the import statement so you can paste it directly into your project. Vanilla JS examples use Intl.DateTimeFormat for formatting where possible — it's built into every modern browser and Node.js, and handles locales correctly.

Method Comparison

The same operation across all three approaches. Use this to choose the right tool or translate between them.

OperationVanilla JSdayjsdate-fns
Current datenew Date()dayjs()new Date()
From stringnew Date('2026-03-26')dayjs('2026-03-26')parseISO('2026-03-26')
Formatd.toLocaleDateString()d.format('YYYY-MM-DD')format(d, 'yyyy-MM-dd')
Add 7 daysd.setDate(d.getDate()+7)d.add(7, 'day')addDays(d, 7)
Subtract 3 monthsd.setMonth(d.getMonth()-3)d.subtract(3, 'month')subMonths(d, 3)
Diff in days(b-a)/86400000b.diff(a, 'day')differenceInDays(b, a)
Start of monthnew Date(y, m, 1)d.startOf('month')startOfMonth(d)
Is before?a < ba.isBefore(b)isBefore(a, b)
Is valid?!isNaN(d.getTime())d.isValid()isValid(d)
UTCd.toISOString()dayjs.utc()d.toISOString()
Epoch (ms)Date.now()dayjs().valueOf()getTime(d)
Epoch (sec)Date.now()/1000|0dayjs().unix()getUnixTime(d)

Library Comparison

FeatureVanilla JSdayjsdate-fns
InstallBuilt-innpm i dayjsnpm i date-fns
Bundle size0 KB~2 KB gzipTree-shakeable (per-function)
API styleOOP (mutable)OOP (immutable, chainable)Functional (pure functions)
ImmutableNo — methods mutateYes — returns new instanceYes — returns new Date
Timezone supportIntl.DateTimeFormatPlugin: dayjs/plugin/utc + timezonedate-fns-tz package
Locale supportIntl (browser-native)Plugin: per-locale filesBuilt-in locale modules
TypeScriptBuilt-in typesBuilt-in typesBuilt-in types
Moment.js drop-in?NoYes (nearly identical API)No (different paradigm)
Best forSimple ops, no depsMoment.js migration, small bundlesLarge apps, tree-shaking

Intl.DateTimeFormat Options

The built-in Intl.DateTimeFormat is the most powerful vanilla formatting tool. It handles locales, timezones, and calendar systems natively.

OptionValuesExample output
year'numeric' | '2-digit'2026 | 26
month'numeric' | '2-digit' | 'long' | 'short' | 'narrow'3 | 03 | March | Mar | M
day'numeric' | '2-digit'26 | 26
weekday'long' | 'short' | 'narrow'Thursday | Thu | T
hour'numeric' | '2-digit'2 | 02
minute'numeric' | '2-digit'30 | 30
second'numeric' | '2-digit'45 | 45
hour12true | false2:30 PM | 14:30
timeZoneIANA string'America/New_York'
timeZoneName'long' | 'short'Eastern Daylight Time | EDT

dayjs Format Tokens

TokenMeaningExample
YYYY4-digit year2026
YY2-digit year26
MMMonth (zero-padded)03
MMonth (no padding)3
DDDay (zero-padded)26
DDay (no padding)26
HHHour, 24h (zero-padded)14
hhHour, 12h (zero-padded)02
mmMinute30
ssSecond45
AAM/PMPM
ddddFull weekdayThursday
dddShort weekdayThu
MMMMFull month nameMarch
MMMShort month nameMar
ZUTC offset-05:00
XUnix seconds (advancedFormat plugin)1774533600
xUnix milliseconds (advancedFormat plugin)1774533600000

Common Gotchas

JavaScript's Date API has well-known traps. Knowing these saves hours of debugging.

GotchaWhat happensFix
Month is 0-indexednew Date(2026, 0, 1) = Jan 1Remember: 0=Jan, 11=Dec
ISO string parsed as UTCnew Date('2026-01-01') = Dec 31 localAdd time: '2026-01-01T00:00:00' or use constructor
Non-ISO parsed as localnew Date('01/01/2026') = Jan 1 localInconsistent — avoid string parsing
Date methods mutated.setDate(d.getDate()+1) changes dClone first: new Date(d)
Invalid date is silentnew Date('garbage') doesn't throwCheck: isNaN(d.getTime())
getYear() vs getFullYear()getYear() returns year - 1900Always use getFullYear()

Common Patterns & Recipes

Format a date for display

Get relative time ("3 hours ago")

List all dates in a range

Frequently Asked Questions

How do I get the current date in JavaScript?

new Date() gives the current date and time. For a formatted string: new Date().toLocaleDateString(). For ISO format: new Date().toISOString(). Remember that getMonth() is zero-indexed — January is 0, not 1.

Should I use dayjs or date-fns?

dayjs if you want a Moment.js-like chainable API in ~2KB: dayjs().add(7, 'day').format('YYYY-MM-DD'). date-fns if you want tree-shakeable pure functions: format(addDays(new Date(), 7), 'yyyy-MM-dd'). Both are well-maintained and have TypeScript support. dayjs is simpler; date-fns is more bundle-efficient in large projects.

How do I format a date without a library?

Use Intl.DateTimeFormat: new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' }).format(date) gives "March 26, 2026". For ISO: date.toISOString().slice(0, 10). For custom formats, toLocaleDateString with options handles most cases without a library.

Why does new Date('2026-01-01') give the wrong day?

ISO date strings without a time component are parsed as UTC midnight. In US time zones, UTC midnight is still December 31 local time. Fix: use new Date('2026-01-01T00:00:00') (parsed as local) or the constructor new Date(2026, 0, 1) (month is 0-indexed).

How do I add days to a date in JavaScript?

Vanilla: const d = new Date(); d.setDate(d.getDate() + 30) — but this mutates d. dayjs: dayjs().add(30, 'day') — immutable, returns new instance. date-fns: addDays(new Date(), 30) — returns a new Date. For months/years, dayjs and date-fns handle month boundaries correctly; vanilla requires more care.

How do I calculate the difference between two dates?

Vanilla: Math.round((date2 - date1) / 86400000) for days (86400000 = ms per day). dayjs: dayjs(date2).diff(dayjs(date1), 'day'). date-fns: differenceInDays(date2, date1). For months or years, use a library — manual month/year math is error-prone due to variable month lengths.

Related Tools