
Dayjs
- 8 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Helps with ai & agent building tasks.
About
dayjs is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- dayjs
- AI & Agent Building
- AI-coding skill
Dayjs by the numbers
- 8 all-time installs (skills.sh)
- Ranked #12,321 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill dayjsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 8 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Day.js API リファレンス
Day.js 公式ドキュメントの全 API を網羅したスキル。 ユーザーのタスクに応じて適切な README.md を読み、そこから個別ファイルへ辿ること。
ディレクトリ構成
skills/dayjs/
SKILL.md
references/
installation/
README.md
installation.md
parse/
README.md
parse.md
get-set/
README.md
get-set.md
manipulate/
README.md
manipulate.md
display/
README.md
display.md
query/
README.md
query.md
i18n/
README.md
i18n.md
plugin/
README.md
plugin-overview.md
format-plugins.md
display-plugins.md
getset-plugins.md
parse-plugins.md
query-plugins.md
timezone-utc-plugins.md
other-plugins.md
customization/
README.md
customization.md
durations/
README.md
durations.md
timezone/
README.md
timezone.md
samples/
README.md
basic-parsing.md
custom-format-parsing.md
formatting.md
add-subtract.md
start-end-of.md
comparison.md
relative-time.md
locale.md
timezone.md
duration.md
scripts/
README.md
install.md
plugin.md
i18n.md
customization.md
test.md探索手順
タスクからカテゴリを引き、カテゴリの README.md で目的のページを特定する:
1. 下記マッピング表でタスクに対応するカテゴリを探す 2. そのカテゴリの references/{category}/README.md を参照して目的のページを特定する 3. 該当ページの .md を Read して詳細を確認する
タスク → カテゴリ マッピング
| タスク | カテゴリ | 参照 README |
|---|---|---|
| npm install、CDN 読み込み、TypeScript 設定 | installation | references/installation/README.md |
| dayjs() でオブジェクト生成、文字列パース、Unix タイムスタンプ、clone、isValid | parse | references/parse/README.md |
| millisecond〜year の取得・設定、weekday、quarter、max、min | get-set | references/get-set/README.md |
| add、subtract、startOf、endOf、utcOffset による日時操作 | manipulate | references/manipulate/README.md |
| format、fromNow、diff、unix、toDate、toJSON、toISOString | display | references/display/README.md |
| isBefore、isSame、isAfter、isBetween、isDayjs、isLeapYear | query | references/query/README.md |
| ロケール読み込み、言語切り替え、月名・曜日名一覧 | i18n | references/i18n/README.md |
| AdvancedFormat、RelativeTime、Duration、UTC、Timezone 等プラグイン | plugin | references/plugin/README.md |
| 月名・曜日名カスタマイズ、相対時間テンプレート、カスタムロケール | customization | references/customization/README.md |
| dayjs.duration()、humanize、format、as、get | durations | references/durations/README.md |
| dayjs.tz()、タイムゾーン変換、デフォルトタイムゾーン設定 | timezone | references/timezone/README.md |
| 典型的な使い方を知りたい | samples | samples/README.md |
| インストール・CLI コマンド・プラグイン設定を知りたい | scripts | scripts/README.md |
Day.js — Customization
Day.js is very easy to customize. You can create new locales or modify existing ones using the updateLocale plugin.
Customization (Overview)
Creating Custom Locales
var localeObject = {...} // Day.js locale Object
dayjs.locale('en-my-settings', localeObject);Updating Existing Locales
Requires the UpdateLocale plugin:
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
/**/
})Full Locale Object Template
const localeObject = {
name: 'es',
weekdays: 'Domingo_Lunes ...'.split('_'),
weekdaysShort: 'Sun_M'.split('_'), // optional
weekdaysMin: 'Su_Mo'.split('_'), // optional
weekStart: 1, // optional, 1 = Monday
yearStart: 4, // optional
months: 'Enero_Febrero ... '.split('_'),
monthsShort: 'Jan_F'.split('_'), // optional
ordinal: n => `${n}º`,
formats: {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A',
l: 'D/M/YYYY',
ll: 'D MMM, YYYY',
lll: 'D MMM, YYYY h:mm A',
llll: 'ddd, MMM D, YYYY h:mm A'
},
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years'
},
meridiem: (hour, minute, isLowercase) => {
return hour > 12 ? 'PM' : 'AM'
}
}Creating Locale Files
Structure for locale files (e.g., dayjs/locale/es.js):
import dayjs from 'dayjs'
const locale = { ... }
dayjs.locale(locale, null, true)
export default locale---
Month Names (Locale#months)
Locale#months should be an array of full month names. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
months: [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
})Function-Based Month Names
For scenarios requiring conditional logic based on formatting context:
dayjs.updateLocale("en", {
months: function (dayjsInstance, format) {
// dayjsInstance: the Day.js object being formatted
// format: the formatting string
if (/^MMMM/.test(format)) {
return monthShortFormat[dayjsInstance.month()];
} else {
return monthShortStandalone[dayjsInstance.month()];
}
},
});---
Month Abbreviations (Locale#monthsShort)
Locale#monthsShort should be an array of abbreviated month names. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
monthsShort: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
})monthsShort can also accept a callback function, similar to Locale#months.
---
Weekday Names (Locale#weekdays)
Locale#weekdays should be an array of the weekday names. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
weekdays: [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
]
})---
Weekday Abbreviations (Locale#weekdaysShort)
Locale#weekdaysShort should be an array of abbreviated weekday names. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
})- The array follows the standard week order (Sunday through Saturday).
- This customization applies globally once set.
---
Minimal Weekday Abbreviations (Locale#weekdaysMin)
Locale#weekdaysMin enables configuration of minimal two-letter weekday abbreviations. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
weekdaysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
})---
Relative Time (Locale#relativeTime)
Locale#relativeTime provides replacement strings for the dayjs#from method. Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
relativeTime: {
future: "in %s",
past: "%s ago",
s: 'a few seconds',
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
}
})Configuration Properties
| Key | Description |
|---|---|
future | Prefix/suffix applied to future dates (%s is replaced with the value) |
past | Prefix/suffix applied to past dates (%s is replaced with the value) |
s, m, h, d, M, y | Singular forms (a few seconds, a minute, an hour, a day, a month, a year) |
mm, hh, dd, MM, yy | Plural forms (%d is replaced with the count) |
Advanced: Function Token
For locales requiring special processing, tokens can be defined as functions:
relativeTime: {
yy: function (number, withoutSuffix, key, isFuture) {
return string;
}
}Function Parameters:
| Parameter | Description |
|---|---|
number | Unit count for the specified key |
withoutSuffix | Boolean indicating if suffix display is omitted |
key | The replacement key identifier |
isFuture | Boolean for future vs. past context |
Thresholds and Rounding
var config = {
thresholds: [{}],
rounding: function
}
dayjs.extend(relativeTime, config)Default threshold example:
var thresholds = [
{ l: 's', r: 1 },
{ l: 'm', r: 1 },
{ l: 'mm', r: 59, d: 'minute' },
{ l: 'h', r: 1 },
{ l: 'hh', r: 23, d: 'hour' },
{ l: 'd', r: 1 },
{ l: 'dd', r: 29, d: 'day' },
{ l: 'M', r: 1 },
{ l: 'MM', r: 11, d: 'month' },
{ l: 'y', r: 1 },
{ l: 'yy', d: 'year' }
]Custom threshold keys can be added and matched with locale updates:
var thresholds = [
...,
{ l: 'ss', r: 59, d: 'second' }
]
dayjs.updateLocale('en', {
relativeTime: {
...,
ss: "%d seconds"
}
})The rounding function processes numeric values before formatting. Default is Math.round; alternatives like Math.floor can be substituted.
---
Calendar (Locale#calendar)
Locale#calendar allows defining how dates are displayed in relative calendar format (e.g., "Yesterday", "Today", "Tomorrow"). Requires the UpdateLocale plugin.
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
calendar: {
lastDay: '[Yesterday at] LT',
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
lastWeek: '[last] dddd [at] LT',
nextWeek: 'dddd [at] LT',
sameElse: 'L'
}
})Configuration Keys
| Key | Description |
|---|---|
lastDay | Format for dates one day in the past |
sameDay | Format for the current date |
nextDay | Format for dates one day in the future |
lastWeek | Format for dates in the previous week |
nextWeek | Format for dates in the upcoming week |
sameElse | Fallback format for all other dates |
Advanced: Callback Functions
Calendar values can be defined as callback functions. The function receives a Day.js object representing "now" as the first parameter, and this refers to the current Day.js instance:
function callback (now) {
return '[hoy a la' + ((this.hour() !== 1) ? 's' : '') + ']' + now.format();
}customization
| Name | Description | Path |
|---|---|---|
| Day.js — Customization | Day.js is very easy to customize. You can create… | customization.md |
Day.js — Display
Once parsing and manipulation are done, you need some way to display the Day.js object. This section covers all display and output methods.
---
format
Get the formatted date according to the string of tokens passed in. To escape characters, wrap them in square brackets (e.g., [MM]).
dayjs().format()
// current date in ISO8601, without fraction seconds e.g. '2020-04-02T08:02:17-05:00'
dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]')
// 'YYYYescape 2019-01-25T00:00:00-02:00Z'
dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'Format Tokens
| Token | Output | Description |
|---|---|---|
YY | 18 | Two-digit year |
YYYY | 2018 | Four-digit year |
M | 1-12 | Month, starting at 1 |
MM | 01-12 | Month, 2-digits |
MMM | Jan-Dec | Abbreviated month name |
MMMM | January-December | Full month name |
D | 1-31 | Day of month |
DD | 01-31 | Day of month, 2-digits |
d | 0-6 | Day of week (Sunday = 0) |
dd | Su-Sa | Min name of day of week |
ddd | Sun-Sat | Short day name |
dddd | Sunday-Saturday | Full day name |
H | 0-23 | Hour (24-hour) |
HH | 00-23 | Hour (24-hour), 2-digits |
h | 1-12 | Hour (12-hour clock) |
hh | 01-12 | Hour (12-hour), 2-digits |
m | 0-59 | Minute |
mm | 00-59 | Minute, 2-digits |
s | 0-59 | Second |
ss | 00-59 | Second, 2-digits |
SSS | 000-999 | Millisecond, 3-digits |
Z | +05:00 | UTC offset, ±HH:mm |
ZZ | +0500 | UTC offset, ±HHmm |
A | AM PM | Meridiem (uppercase) |
a | am pm | Meridiem (lowercase) |
Localized Formats
Requires the LocalizedFormat plugin:
dayjs.extend(LocalizedFormat)
dayjs().format('L LT')| Token | English Output | Example |
|---|---|---|
LT | h:mm A | 8:02 PM |
LTS | h:mm:ss A | 8:02:18 PM |
L | MM/DD/YYYY | 08/16/2018 |
LL | MMMM D, YYYY | August 16, 2018 |
LLL | MMMM D, YYYY h:mm A | August 16, 2018 8:02 PM |
LLLL | dddd, MMMM D, YYYY h:mm A | Thursday, August 16, 2018 8:02 PM |
l | M/D/YYYY | 8/16/2018 |
ll | MMM D, YYYY | Aug 16, 2018 |
lll | MMM D, YYYY h:mm A | Aug 16, 2018 8:02 PM |
llll | ddd, MMM D, YYYY h:mm A | Thu, Aug 16, 2018 8:02 PM |
Additional formats (Q,Do,k,kk,X,x) are available through theAdvancedFormatplugin.
---
fromNow
Returns the string of relative time from now. Requires the RelativeTime plugin.
dayjs.extend(relativeTime)
dayjs('1999-01-01').fromNow() // '22 years ago'
dayjs('1999-01-01').fromNow(true) // '22 years' (without suffix)Breakdown Range
| Range | Key | Sample Output |
|---|---|---|
| 0 to 44 seconds | s | a few seconds ago |
| 45 to 89 seconds | m | a minute ago |
| 90 seconds to 44 minutes | mm | 2 minutes ago ... 44 minutes ago |
| 45 to 89 minutes | h | an hour ago |
| 90 minutes to 21 hours | hh | 2 hours ago ... 21 hours ago |
| 22 to 35 hours | d | a day ago |
| 36 hours to 25 days | dd | 2 days ago ... 25 days ago |
| 26 to 45 days | M | a month ago |
| 46 days to 10 months | MM | 2 months ago ... 10 months ago |
| 11 months to 17 months | y | a year ago |
| 18 months+ | yy | 2 years ago ... 20 years ago |
---
from
Returns a relative time string from a reference date. Requires the RelativeTime plugin.
dayjs.extend(relativeTime)
var a = dayjs('2000-01-01')
dayjs('1999-01-01').from(a) // 'a year ago'
dayjs('1999-01-01').from(a, true) // 'a year' (without suffix)---
toNow
Returns the relative time from a date to now. Requires the RelativeTime plugin.
dayjs.extend(relativeTime)
dayjs('1999-01-01').toNow() // 'in 22 years'
dayjs('1999-01-01').toNow(true) // '22 years' (without suffix)toNow()is the inverse offromNow()— it shows how much time remains until now from a past date.
---
to
Returns a relative time string to a reference date. Requires the RelativeTime plugin.
dayjs.extend(relativeTime)
var a = dayjs('2000-01-01')
dayjs('1999-01-01').to(a) // 'in a year'
dayjs('1999-01-01').to(a, true) // 'a year' (without suffix)---
calendar
Displays time relative to a given reference time (defaults to now), formatted contextually. Requires the Calendar plugin.
dayjs.extend(calendar)
dayjs().calendar()
dayjs().calendar(dayjs('2008-01-01'))Default Output Keys
| Key | Display Value |
|---|---|
lastWeek | Last Monday at 2:30 AM |
lastDay | Yesterday at 2:30 AM |
sameDay | Today at 2:30 AM |
nextDay | Tomorrow at 2:30 AM |
nextWeek | Sunday at 2:30 AM |
sameElse | 7/10/2011 |
Custom Format
dayjs().calendar(null, {
sameDay: '[Today at] h:mm A',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
})To escape characters, wrap them in square brackets (e.g., [Today]).---
diff
Calculates the difference between two date-time values in the specified unit.
const date1 = dayjs('2019-01-25')
const date2 = dayjs('2018-06-05')
date1.diff(date2) // 20214000000 (default: milliseconds)
date1.diff('2018-06-05', 'month') // 7
date1.diff('2018-06-05', 'month', true) // 7.645161290322581 (float)Available Units
| Unit | Shorthand | Description |
|---|---|---|
day | d | Day |
week | w | Week of Year |
quarter | Q | Quarter |
month | M | Month |
year | y | Year |
hour | h | Hour |
minute | m | Minute |
second | s | Second |
millisecond | ms | Millisecond |
Units are case insensitive and support plural and short forms. Short forms are case sensitive.
---
valueOf
Returns the number of milliseconds since the Unix Epoch.
dayjs('2019-01-25').valueOf() // 1548381600000
+dayjs(1548381600000) // 1548381600000---
unix
Returns the number of seconds since the Unix Epoch, floored to the nearest second (no milliseconds).
dayjs('2019-01-25').unix() // 1548381600---
daysInMonth
Returns the number of days in the current month.
dayjs('2019-01-25').daysInMonth() // 31---
toDate
Returns a copy of the native JavaScript Date object parsed from the Day.js instance.
dayjs('2019-01-25').toDate()---
toArray
Returns an array mirroring the date's parameters. Requires the ToArray plugin.
dayjs.extend(toArray)
dayjs('2019-01-25').toArray()
// [ 2019, 0, 25, 0, 0, 0, 0 ]
// [ year, monthIndex, day, hour, minute, second, millisecond ]Month index is 0-based (January = 0).
---
toJSON
Serializes the Day.js object as an ISO 8601 string (suitable for JSON).
dayjs('2019-01-25').toJSON() // '2019-01-25T02:00:00.000Z'---
toISOString
Returns an ISO 8601 formatted string representation.
dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z'---
toObject
Returns a plain object containing the date's properties. Requires the ToObject plugin.
dayjs.extend(toObject)
dayjs('2019-01-25').toObject()
/* {
years: 2019,
months: 0,
date: 25,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
} */months is 0-indexed (January = 0).---
toString
Returns a human-readable string representation of the date.
dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT'Display
| Name | Description | Path |
|---|---|---|
| Day.js — Display | Once parsing and manipulation are done, you need some way to display the Day.js object. This section covers all display and output methods. | display.md |
Day.js — Durations
Duration objects represent a length of time (not a specific point in time). They are contextless — "2 hours" rather than "between 2 and 4 pm today." Unit conversions that require context (e.g., how many days in a year) are not reliable on durations; use dayjs#diff instead.
Requires: Duration plugin
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)---
Creating
dayjs.duration(100) // 100 milliseconds
dayjs.duration(2, 'days') // 2 days
dayjs.duration({
seconds: 2, minutes: 2, hours: 2,
days: 2, weeks: 2, months: 2, years: 2
})
dayjs.duration('P1Y2M3DT4H5M6S') // ISO 8601
dayjs.duration('P1M')Available Units
| Unit | Shorthand |
|---|---|
| years | y |
| months | M |
| weeks | w |
| days | d |
| hours | h |
| minutes | m |
| seconds | s |
| milliseconds | ms |
---
Clone
Returns a clone of the duration object.
dayjs.duration().clone()---
Humanize
Displays a duration in human-readable text. Requires the RelativeTime plugin in addition to Duration.
Requires: Duration plugin + RelativeTime plugin
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)
dayjs.duration(1, 'minutes').humanize() // "a minute"
dayjs.duration(2, 'minutes').humanize() // "2 minutes"
dayjs.duration(24, 'hours').humanize() // "a day"
// With suffix
dayjs.duration(1, 'minutes').humanize(true) // "in a minute"
// Past (negative value)
dayjs.duration(-1, 'minutes').humanize(true) // "a minute ago"---
Format
Returns a formatted string based on a token string. Wrap literal characters in square brackets to escape them.
dayjs.duration({
seconds: 1, minutes: 2, hours: 3,
days: 4, months: 6, years: 7
}).format('YYYY-MM-DDTHH:mm:ss')
// "0007-06-04T03:02:01"Format Tokens
| Token | Output | Description |
|---|---|---|
Y | 18 | Years (1-digit) |
YY | 18 | Years (2-digit) |
YYYY | 2018 | Years (4-digit) |
M | 1-12 | Months |
MM | 01-12 | Months (zero-padded) |
D | 1-31 | Days |
DD | 01-31 | Days (zero-padded) |
H | 0-23 | Hours |
HH | 00-23 | Hours (zero-padded) |
m | 0-59 | Minutes |
mm | 00-59 | Minutes (zero-padded) |
s | 0-59 | Seconds |
ss | 00-59 | Seconds (zero-padded) |
SSS | 000-999 | Milliseconds |
---
Milliseconds
.milliseconds() returns the milliseconds component (0–999). .asMilliseconds() returns the total duration in milliseconds.
dayjs.duration(500).milliseconds() // 500
dayjs.duration(1500).milliseconds() // 500
dayjs.duration(15000).milliseconds() // 0
dayjs.duration(500).asMilliseconds() // 500
dayjs.duration(1500).asMilliseconds() // 1500
dayjs.duration(15000).asMilliseconds()// 15000---
Seconds
.seconds() returns the seconds component (0–59). .asSeconds() returns the total duration in seconds.
dayjs.duration(500).seconds() // 0
dayjs.duration(1500).seconds() // 1
dayjs.duration(15000).seconds() // 15
dayjs.duration(500).asSeconds() // 0.5
dayjs.duration(1500).asSeconds() // 1.5
dayjs.duration(15000).asSeconds()// 15---
Minutes
.minutes() returns the minutes component (0–59). .asMinutes() returns the total duration in minutes.
dayjs.duration().minutes()
dayjs.duration().asMinutes()---
Hours
.hours() returns the hours component (0–23). .asHours() returns the total duration in hours.
dayjs.duration().hours()
dayjs.duration().asHours()---
Days
.days() returns the days component (0–30). .asDays() returns the total duration in days.
dayjs.duration().days()
dayjs.duration().asDays()---
Weeks
.weeks() returns the weeks component (0–4). .asWeeks() returns the total duration in weeks.
Note: weeks are counted as a subset of days and are not deducted from the days count. One week = 7 days.
dayjs.duration().weeks()
dayjs.duration().asWeeks()---
Months
.months() returns the months component (0–11). .asMonths() returns the total duration in months.
dayjs.duration().months()
dayjs.duration().asMonths()---
Years
.years() returns the years component. .asYears() returns the total duration in years.
dayjs.duration().years()
dayjs.duration().asYears()---
Add
Returns a cloned duration with a specified amount of time added.
var a = dayjs.duration(1, 'd')
var b = dayjs.duration(2, 'd')
a.add(b).days() // 3 — pass another duration
a.add({ days: 2 }).days() // 3 — pass an object
a.add(2, 'days').days() // 3 — pass value + unit string---
Subtract
Returns a cloned duration with a specified amount of time subtracted.
var a = dayjs.duration(3, 'd')
var b = dayjs.duration(2, 'd')
a.subtract(b).days() // 1
a.subtract({ days: 2 }).days() // 1
a.subtract(2, 'days').days() // 1---
Using Duration with Diff
Pass the result of dayjs#diff to dayjs.duration() to get a duration object representing the time between two dates.
var x = dayjs()
var y = dayjs()
var d = dayjs.duration(x.diff(y))
// duration object with the difference between x and ySee also: Difference display docs
---
As Unit of Time
Alternative syntax to Duration#asX methods.
var d = dayjs.duration(/* ... */)
d.as('hours')
d.as('minutes')
d.as('seconds')
d.as('milliseconds')---
Get Unit of Time
Alternative syntax to individual getter methods. Returns the component value (not the total as-X value).
var d = dayjs.duration(/* ... */)
d.get('hours')
d.get('minutes')
d.get('seconds')
d.get('milliseconds')---
As JSON (toJSON)
When serialized to JSON, a duration is represented as an ISO 8601 string automatically.
JSON.stringify({
postDuration: dayjs.duration(5, 'm')
})
// '{"postDuration":"PT5M"}'---
Is a Duration
dayjs.isDuration() returns true only for duration objects created with dayjs.duration().
dayjs.isDuration() // false
dayjs.isDuration(new Date()) // false
dayjs.isDuration(dayjs()) // false
dayjs.isDuration(dayjs.duration()) // true
dayjs.isDuration(dayjs.duration(2, 'minutes')) // true---
As ISO 8601 String (toISOString)
Returns the duration as an ISO 8601 duration string (PnYnMnDTnHnMnS).
dayjs.duration(1, 'd').toISOString() // "P1D"| Symbol | Meaning |
|---|---|
| P | Period designator (always at start) |
| Y | Years |
| M | Months (or Minutes after T) |
| D | Days |
| T | Time designator |
| H | Hours |
| S | Seconds |
---
Locale
Get or set the locale of a duration. Affects string methods like humanize().
Requires: RelativeTime plugin
import 'dayjs/locale/es'
dayjs.duration(1, 'minutes').locale('en').humanize() // "a minute"
dayjs.duration(1, 'minutes').locale('es').humanize() // "un minuto"Durations
| Name | Description | Path |
|---|---|---|
| Day.js — Durations | Duration objects represent a length of time (not a specific point in time). They are contextless — "2 hours" rather than "between 2 and 4 pm… | durations.md |
Day.js — Get + Set
Day.js uses overloaded getters and setters: calling these methods without parameters acts as a getter, and calling them with a parameter acts as a setter. All setter operations return new instances since dayjs objects maintain immutability.
dayjs().second(30).valueOf() // => new Date().setSeconds(30)
dayjs().second() // => new Date().getSeconds()In UTC mode, methods map to their UTC equivalents:
dayjs.utc().second(30).valueOf() // => new Date().setUTCSeconds(30)
dayjs.utc().second() // => new Date().getUTCSeconds()---
Millisecond
Gets or sets the millisecond. Accepts values from 0 to 999. Values outside the range carry over to seconds.
dayjs().millisecond() // getter — returns 0-999
dayjs().millisecond(1) // setter — returns new dayjs object---
Second
Gets or sets the second. Accepts values from 0 to 59. Overflow carries over to minutes.
dayjs().second() // getter — returns 0-59
dayjs().second(1) // setter — returns new dayjs object---
Minute
Gets or sets the minutes. Accepts values from 0 to 59. Overflow carries over to hours.
dayjs().minute() // getter — returns 0-59
dayjs().minute(59) // setter — returns new dayjs object---
Hour
Gets or sets the hour. Accepts values from 0 to 23 (24-hour clock). Overflow cascades to the next day.
dayjs().hour() // getter — returns 0-23
dayjs().hour(12) // setter — returns new dayjs object---
Date of Month
Gets or sets the day of the month. Accepts values from 1 to 31. Overflow carries over to subsequent months.
dayjs#dateis for the date of the month, anddayjs#dayis for the day of the week.
dayjs().date() // getter — returns 1-31
dayjs().date(1) // setter — returns new dayjs object---
Day of Week
Gets or sets the day of the week. Accepts values from 0 (Sunday) to 6 (Saturday). Values outside the range cascade into adjacent weeks.
dayjs#dateis for the date of the month, anddayjs#dayis for the day of the week.
dayjs().day() // getter — returns 0 (Sun) to 6 (Sat)
dayjs().day(0) // setter — returns new dayjs object---
Day of Week (Locale Aware)
Gets or sets the day of the week based on locale settings. Requires the Weekday plugin. The meaning of index 0 depends on the locale's first day of the week.
dayjs.extend(weekday)
// When Sunday is the first day of the week:
dayjs().weekday(-7) // previous Sunday
dayjs().weekday(7) // following Sunday
dayjs().weekday(-5) // last Tuesday
dayjs().weekday(5) // next Friday
// When Monday is the first day of the week:
dayjs().weekday(-7) // previous Monday
dayjs().weekday(7) // following Monday---
ISO Day of Week
Gets or sets the ISO day of the week where Monday = 1 and Sunday = 7. Requires the IsoWeek plugin.
dayjs.extend(isoWeek)
dayjs().isoWeekday() // getter — returns 1 (Mon) to 7 (Sun)
dayjs().isoWeekday(1) // setter — Monday, returns new dayjs object---
Day of Year
Gets or sets the day of the year (1–366). Requires the DayOfYear plugin. Overflow propagates to the year.
dayjs.extend(dayOfYear)
dayjs('2010-01-01').dayOfYear() // 1
dayjs('2010-01-01').dayOfYear(365) // 2010-12-31---
Week of Year
Gets or sets the week of the year. Requires the WeekOfYear plugin.
dayjs.extend(weekOfYear)
dayjs('2018-06-27').week() // 26
dayjs('2018-06-27').week(5) // setter — returns new dayjs object---
Week of Year (ISO)
Gets or sets the ISO week of the year. Requires the IsoWeek plugin.
dayjs.extend(isoWeek)
dayjs().isoWeek() // getter — returns ISO week number
dayjs().isoWeek(2) // setter — returns new dayjs object---
Month
Gets or sets the month. Accepts values from 0 to 11. Months are zero-indexed: January = 0, December = 11. Overflow carries over to the year.
dayjs().month() // getter — returns 0-11
dayjs().month(0) // setter — January, returns new dayjs object
dayjs().month(11) // setter — December, returns new dayjs object---
Quarter
Gets or sets the quarter of the year (1–4). Requires the QuarterOfYear plugin.
- Q1: January–March
- Q2: April–June
- Q3: July–September
- Q4: October–December
dayjs.extend(quarterOfYear)
dayjs('2010-04-01').quarter() // 2
dayjs('2010-04-01').quarter(2) // setter — returns new dayjs object---
Year
Gets or sets the year.
dayjs().year() // getter — returns current year
dayjs().year(2000) // setter — returns new dayjs object---
Week Year
Gets the week-year according to the current locale. Requires the WeekYear and WeekOfYear plugins.
dayjs.extend(weekYear)
dayjs.extend(weekOfYear)
dayjs().weekYear() // getter — returns locale-aware week-year---
Week Year (ISO)
Gets the ISO week-year. Requires the IsoWeek plugin.
dayjs.extend(isoWeek)
dayjs().isoWeekYear() // getter — returns ISO week-year---
Weeks In Year (ISO)
Gets the number of ISO weeks in the year (52 or 53). Requires the IsoWeeksInYear and IsLeapYear plugins.
dayjs.extend(isoWeeksInYear)
dayjs.extend(isLeapYear)
dayjs('2004-01-01').isoWeeksInYear() // 53
dayjs('2005-01-01').isoWeeksInYear() // 52---
Get
Generic string getter. Retrieves the corresponding information using a unit string. Equivalent to calling the unit method directly.
dayjs().get(unit) === dayjs()[unit]()Units are case-insensitive and support plural and short forms (short forms are case-sensitive).
dayjs().get('year')
dayjs().get('month') // starts at 0
dayjs().get('date')
dayjs().get('hour')
dayjs().get('minute')
dayjs().get('second')
dayjs().get('millisecond')Available Units
| Unit | Shorthand | Description |
|---|---|---|
date | D | Date of Month |
day | d | Day of Week (Sunday=0, Saturday=6) |
month | M | Month (January=0, December=11) |
year | y | Year |
hour | h | Hour |
minute | m | Minute |
second | s | Second |
millisecond | ms | Millisecond |
---
Set
Generic setter. Accepts a unit string and a value, returns a new instance with the changes applied. Equivalent to calling the unit method directly with a value.
dayjs().set(unit, value) === dayjs()[unit](value)Units are case-insensitive and support plural and short forms. Returns a new instance (immutable).
dayjs().set('date', 1)
dayjs().set('month', 3) // April
dayjs().set('second', 30)
// Chaining
dayjs().set('hour', 5).set('minute', 55).set('second', 15)For available units, see the Get section above.
---
Maximum
Returns the latest (furthest future) Day.js instance from a collection. Requires the MinMax plugin.
dayjs.extend(minMax)
// Multiple arguments
dayjs.max(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'))
// Array input
dayjs.max([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])---
Minimum
Returns the earliest (furthest past) Day.js instance from a collection. Requires the MinMax plugin.
dayjs.extend(minMax)
// Multiple arguments
dayjs.min(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'))
// Array input
dayjs.min([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])Get + Set
| Name | Description | Path |
|---|---|---|
| Day.js — Get + Set | Day.js uses overloaded getters and setters: calling these methods without parameters acts as a getter, and calling them with a parameter acts as a setter. | get-set.md |
i18n
Day.js has great support for internationalization. Locales must be explicitly loaded—they are not included in builds by default. Multiple locales can be loaded simultaneously with easy switching between them.
A full list of supported locales is available in the GitHub repository. A locale.json file containing all supported locales is available at the root of each release via CDN.
Loading Locale in Node.js
Load locales on-demand. Locales can be applied globally or to specific instances.
require('dayjs/locale/de')
// import 'dayjs/locale/de' // ES 2015
dayjs.locale('de') // use locale globally
dayjs().locale('de').format() // use locale in a specific instanceTo store the locale object for further use:
var locale_de = require('dayjs/locale/de')
// import locale_de from 'dayjs/locale/de' // ES 2015Loading Locale in the Browser
Via script tag — apply globally or per instance
<script src="path/to/dayjs/locale/de"></script>
<script>
dayjs.locale('de') // use locale globally
dayjs().locale('de').format() // use locale in a specific instance
</script>Access locale object via window property
Locales are exposed as window.dayjs_locale_NAME (hyphens replaced by underscores).
<script src="path/to/dayjs/locale/de"></script>
<script>
var customLocale = window.dayjs_locale_zh_cn // zh-cn -> zh_cn
</script>Via CDN (jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/locale/zh-cn.js"></script>
<script>dayjs.locale('zh-cn')</script>Changing Locale Globally
By default, Day.js comes with English locale only. Load and activate another locale globally with dayjs.locale().
require('dayjs/locale/de')
dayjs.locale('de') // use loaded locale globally
dayjs.locale('en') // switch back to default English locale globallyNote: Changing the global locale does not affect existing instances. Only newly created Day.js objects will use the newly set locale.
Instance Locale (Changing Locale Locally)
Apply a locale to a specific instance instead of globally. .locale() on an instance returns a new instance with the locale applied, leaving the global configuration unchanged.
require('dayjs/locale/de')
dayjs().locale('de').format() // use loaded locale locallyThis is useful when formatting date-times in different locales simultaneously without affecting global state.
Getting Locale
Retrieve the locale code of the current global Day.js instance by calling dayjs.locale() with no arguments.
dayjs.locale() // 'en'Returns a string representing the current locale identifier (e.g., 'en').
Listing Months and Weekdays
Requires the LocaleData plugin.
dayjs.extend(localeData)
dayjs.weekdays() // full weekday names
dayjs.weekdaysShort() // abbreviated weekday names
dayjs.weekdaysMin() // minimal weekday abbreviations
dayjs.months() // full month names
dayjs.monthsShort() // abbreviated month namesExample output of dayjs.months():
['January','February','March','April','May','June','July','August','September','October','November','December']Locale Data
Access locale-specific properties via dayjs.localeData() (global) or dayjs().localeData() (instance). Requires the LocaleData plugin.
Global locale data
dayjs.extend(localeData)
const globalLocaleData = dayjs.localeData()
globalLocaleData.firstDayOfWeek() // first day of week for the locale
globalLocaleData.months() // full month names array
globalLocaleData.monthsShort() // abbreviated month names array
globalLocaleData.weekdays() // full weekday names array
globalLocaleData.weekdaysShort() // abbreviated weekday names array
globalLocaleData.weekdaysMin() // minimal weekday abbreviations array
globalLocaleData.longDateFormat('L') // long date format string for token
globalLocaleData.meridiem() // AM/PM string for the locale
globalLocaleData.ordinal() // ordinal string for a number
// Pass a dayjs instance to get locale-formatted value for that date
globalLocaleData.months(dayjs())
globalLocaleData.monthsShort(dayjs())
globalLocaleData.weekdays(dayjs())
globalLocaleData.weekdaysShort(dayjs())
globalLocaleData.weekdaysMin(dayjs())Instance locale data
const instanceLocaleData = dayjs().localeData()
instanceLocaleData.firstDayOfWeek()
instanceLocaleData.months()
instanceLocaleData.monthsShort()
instanceLocaleData.weekdays()
instanceLocaleData.weekdaysShort()
instanceLocaleData.weekdaysMin()
instanceLocaleData.longDateFormat('L')
instanceLocaleData.meridiem()
instanceLocaleData.ordinal()Available methods summary
| Method | Description |
|---|---|
firstDayOfWeek() | Returns the first day of the week for the locale (0 = Sunday) |
months() | Returns full month names array |
monthsShort() | Returns abbreviated month names array |
weekdays() | Returns full weekday names array |
weekdaysShort() | Returns abbreviated weekday names array |
weekdaysMin() | Returns minimal weekday abbreviations array |
longDateFormat('L') | Returns the long date format string for the given token (requires LocalizedFormat plugin) |
meridiem() | Returns the meridiem string (AM/PM) for the locale |
ordinal() | Returns the ordinal string for a number in the locale |
i18n
| Name | Description | Path |
|---|---|---|
| i18n | Day.js has great support for internationalization… | i18n.md |
Installation
Day.js is a lightweight JavaScript library for date/time manipulation designed to work in both the browser and Node.js.
Installation Overview
All code works in both browser and Node.js environments. Unit tests are run in both environments.
Browser Support
- Chrome on Windows XP
- Internet Explorer 8, 9, 10 on Windows 7
- Internet Explorer 11 on Windows 10
- Latest Firefox on Linux
- Latest Safari on macOS 10.8 and 10.11
Node.js
Install via a package manager:
npm install dayjs
# or
yarn add dayjs
# or
pnpm add dayjsImport and use:
const dayjs = require('dayjs')
// import dayjs from 'dayjs' // ES 2015
dayjs().format()Both CommonJS require syntax and ES 2015 import statements are supported.
Browser
Include via a local script tag:
<script src="path/to/dayjs/dayjs.min.js"></script>
<script>
dayjs().format()
</script>Or load from a CDN (jsDelivr):
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script>dayjs().format()</script>Day.js is also available on cdnjs.com and unpkg.
TypeScript
Day.js ships with official type declarations in the NPM package out of the box. No @types package needed.
Install via NPM:
npm install dayjsDefault import (requires esModuleInterop: true or allowSyntheticDefaultImports: true in tsconfig.json):
import dayjs from 'dayjs'
dayjs().format()Namespace import (works without additional tsconfig.json options):
import * as dayjs from 'dayjs'
dayjs().format()Using Locales and Plugins in TypeScript
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear'
import 'dayjs/locale/zh-cn'
dayjs.extend(isLeapYear)
dayjs.locale('zh-cn')tsconfig.json (with default import)
{
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}Download
- CDN / Latest version: https://www.jsdelivr.com/package/npm/dayjs
- Source code & releases: https://github.com/iamkun/dayjs/releases
Notes
- Day.js is ~2kB minified and gzipped
- You can test sample code directly in your browser's developer console
installation
| Name | Description | Path |
|---|---|---|
| Installation | Day.js is a lightweight JavaScript library for date/time manipulation… | installation.md |
Day.js — Manipulate
Once you have a Day.js object, you may want to manipulate it in some way. Day.js supports method chaining for manipulation operations.
dayjs('2019-01-25').add(1, 'day').subtract(1, 'year').year(2009).toString()---
Add
Returns a cloned Day.js object with a specified amount of time added. The original object remains unchanged.
const a = dayjs()
const b = a.add(7, 'day')
// a -> original value, unchanged
// b -> manipulation resultUnits
| Unit | Shorthand | Description |
|---|---|---|
day | d | Day |
week | w | Week |
month | M | Month |
quarter | Q | Quarter (requires QuarterOfYear plugin) |
year | y | Year |
hour | h | Hour |
minute | m | Minute |
second | s | Second |
millisecond | ms | Millisecond |
Units are case-insensitive and support plural and short forms. Short forms are case-sensitive.
Alternative Syntax Using Durations
result = dayjs().add(dayjs.duration({'days' : 1}))Notes
- Decimal values for days and weeks are rounded to the nearest integer before adding.
- Quarter support requires the QuarterOfYear plugin.
---
Subtract
Returns a cloned Day.js object with a specified amount of time subtracted. The original object remains unchanged.
dayjs().subtract(7, 'year')Accepts the same units as add(). Units are case-insensitive and support plural and short forms. Decimal values for days and weeks are rounded to the nearest integer before subtracting.
---
Start of Unit of Time
Returns a cloned Day.js object set to the start of a unit of time.
dayjs().startOf('year')Units
| Unit | Shorthand | Description |
|---|---|---|
year | y | January 1st, 00:00 this year |
quarter | Q | Beginning of current quarter, 1st day of months, 00:00 (requires QuarterOfYear plugin) |
month | M | First day of this month, 00:00 |
week | w | First day of this week, 00:00 (locale aware) |
isoWeek | — | First day of week per ISO 8601, 00:00 (requires IsoWeek plugin) |
date | D | 00:00 today |
day | d | 00:00 today |
hour | h | Current time with 0 mins, 0 secs, 0 ms |
minute | m | Current time with 0 seconds, 0 ms |
second | s | Current time with 0 milliseconds |
Units are case-insensitive and support plural and short forms.
---
End of Unit of Time
Returns a cloned Day.js object set to the end of a unit of time. The original object remains unchanged.
dayjs().endOf('month')Accepts the same units as startOf(). Units are case-insensitive and support plural and short forms.
---
Local
Returns a Day.js object configured to use local time rather than UTC. Requires the UTC plugin.
dayjs.extend(utc)
var a = dayjs.utc()
a.format() // 2019-03-06T00:00:00Z
a.local().format() // 2019-03-06T08:00:00+08:00Notes
- Converts a UTC-based Day.js object to display in the local timezone.
---
UTC
Returns a Day.js object with a flag to use UTC time. Requires the UTC plugin.
dayjs.extend(utc)Standard UTC Conversion
var a = dayjs()
a.format() // 2019-03-06T08:00:00+08:00
a.utc().format() // 2019-03-06T00:00:00ZUTC with Time Preservation
Passing true changes the timezone to UTC without altering the current time value:
dayjs('2016-05-03 22:15:01').utc(true).format()
// 2016-05-03T22:15:01ZNotes
- Passing
truereinterprets the existing time value as UTC rather than converting it.
---
UTC Offset
Gets or sets the UTC offset in minutes. Requires the UTC plugin when setting.
Getting UTC Offset
dayjs().utcOffset() // returns offset in minutesSetting UTC Offset
dayjs.extend(utc)
dayjs().utcOffset(120) // set offset to +02:00When the input value is between -16 and 16, it is interpreted as hours rather than minutes:
dayjs().utcOffset(8) // interpreted as 8 hours (+08:00)
dayjs().utcOffset(480) // 480 minutes = 8 hours (+08:00)Preserving Local Time
Pass true as the second parameter to keep the same local time while changing the offset:
dayjs.utc('2000-01-01T06:01:02Z').utcOffset(1, true).format()
// 2000-01-01T06:01:02+01:00Notes
- The offset remains fixed and does not automatically adjust for daylight saving time rules.
Manipulate
| Name | Description | Path |
|---|---|---|
| Day.js — Manipulate | Once you have a Day.js object, you may want to manipulate it in some way. Day.js supports… | manipulate.md |
Day.js — Parse
Day.js creates a wrapper around the native Date object by calling dayjs() with supported input formats. The Day.js object is immutable — all API operations that change it return a new instance.
---
Parse (Overview)
The dayjs() function accepts the following input types:
- Now (no argument)
- String (ISO 8601)
- String + Format (requires
CustomParseFormatplugin) - Unix Timestamp in milliseconds
- Unix Timestamp in seconds (
dayjs.unix()) - JavaScript
Dateobject - Object (requires
ObjectSupportplugin) - Array (requires
ArraySupportplugin) - UTC (requires
UTCplugin) - Day.js clone
---
Now
Calling dayjs() without parameters returns a fresh Day.js object with the current date and time.
var now = dayjs()Equivalent to dayjs(new Date()).
Special cases:
dayjs(undefined)— treated the same asdayjs()(parameters default to undefined when omitted)dayjs(null)— treated as invalid input; will not be processed
---
String
Parse an ISO 8601 formatted string.
dayjs('2018-04-04T16:00:00.000Z')
dayjs('2018-04-13 19:18:17.040+02:00')
dayjs('2018-04-13 19:18')- Space character is accepted in place of the
Tseparator - UTC offset notation is supported (e.g.,
+02:00) - Millisecond precision is optional
For consistent results parsing anything other than ISO 8601 strings, use String + Format.
---
String + Format
Parse a date using a known format string. Requires the CustomParseFormat plugin.
dayjs.extend(customParseFormat)
dayjs("12-25-1995", "MM-DD-YYYY")Locale-Aware Parsing
Pass locale as the third parameter:
require('dayjs/locale/es')
dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es')Strict Parsing
Pass true as the fourth parameter to enforce exact format matching:
dayjs('1970-00-00', 'YYYY-MM-DD').isValid() // true
dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false
dayjs('1970-00-00', 'YYYY-MM-DD', 'es', true).isValid() // falseMultiple Format Options
dayjs("12-25-2001", ["YYYY", "YYYY-MM-DD"], 'es', true);Parsing Tokens
| Token | Example | Description |
|---|---|---|
| YY | 01 | Two-digit year |
| YYYY | 2001 | Four-digit year |
| M | 1-12 | Month (1-based) |
| MM | 01-12 | Two-digit month |
| MMM | Jan-Dec | Abbreviated month name |
| MMMM | January-December | Full month name |
| D | 1-31 | Day of month |
| DD | 01-31 | Two-digit day |
| H | 0-23 | 24-hour hour |
| HH | 00-23 | Two-digit 24-hour |
| h | 1-12 | 12-hour hour |
| hh | 01-12 | Two-digit 12-hour |
| m | 0-59 | Minutes |
| mm | 00-59 | Two-digit minutes |
| s | 0-59 | Seconds |
| ss | 00-59 | Two-digit seconds |
| S | 0-9 | 1-digit milliseconds |
| SS | 00-99 | 2-digit milliseconds |
| SSS | 000-999 | 3-digit milliseconds |
| Z | -05:00 | UTC offset |
| ZZ | -0500 | Compact UTC offset |
| A | AM PM | Meridiem (uppercase) |
| a | am pm | Meridiem (lowercase) |
| Do | 1st...31st | Ordinal day |
| X | 1410715640.579 | Unix timestamp (seconds) |
| x | 1410715640579 | Unix timestamp (milliseconds) |
Recognized separator characters: -_:.,()/
---
Unix Timestamp (milliseconds)
Create a Day.js object from a Unix timestamp in milliseconds (13-digit integer since Jan 1 1970 12AM UTC).
dayjs(1318781876406)The argument must be a number.
---
Unix Timestamp (seconds)
Create a Day.js object from a Unix timestamp in seconds (10-digit integer). Internally multiplied by 1000.
dayjs.unix(1318781876)Fractional seconds are preserved:
dayjs.unix(1318781876.721)---
Date
Create a Day.js object from a native JavaScript Date object. The Date object is cloned — mutations to the original do not affect the Day.js instance.
var d = new Date(2018, 8, 18)
var day = dayjs(d)---
Object
Create a Day.js object by specifying units as an object. Requires the ObjectSupport plugin.
dayjs.extend(objectSupport)
dayjs({ hour: 15, minute: 10 })
dayjs.utc({ y: 2010, M: 3, d: 5, h: 15, m: 10, s: 3, ms: 123 })
dayjs({ year: 2010, month: 3, day: 5, hour: 15, minute: 10, second: 3, millisecond: 123 })
dayjs({ years: 2010, months: 3, date: 5, hours: 15, minutes: 10, seconds: 3, milliseconds: 123 })Notes:
dayanddateboth refer to the day of the monthdayjs({})returns the current time- Months are 0-indexed (0 = January), matching
new Date(year, month, date)behavior
Supported Property Keys
| Short | Long | Plural |
|---|---|---|
y | year | years |
M | month | months |
d / date | day | date |
h | hour | hours |
m | minute | minutes |
s | second | seconds |
ms | millisecond | milliseconds |
---
Array
Create a Day.js object from an array of numbers mirroring the parameters of new Date(). Requires the ArraySupport plugin.
dayjs.extend(arraySupport)
dayjs([2010, 1, 14, 15, 25, 50, 125]) // February 14th, 3:25:50.125 PM
dayjs.utc([2010, 1, 14, 15, 25, 50, 125])
dayjs([2010]) // January 1st
dayjs([2010, 6]) // July 1st
dayjs([2010, 6, 10]) // July 10thNotes:
dayjs([])with an empty array returns the current time- Months are 0-indexed (0 = January, 1 = February, ...)
- Array order:
[year, month, date, hours, minutes, seconds, milliseconds]
---
UTC
Parse and display dates in Coordinated Universal Time. Requires the UTC plugin.
By default, Day.js works in local time. dayjs.utc() switches all display, getter, and setter operations to UTC.
dayjs.extend(utc)
// Local time
dayjs().format() // 2019-03-06T08:00:00+08:00
// UTC time
dayjs.utc().format() // 2019-03-06T00:00:00ZIn UTC mode, all accessors use Date#getUTC* / Date#setUTC* internally:
dayjs.utc().seconds(30).valueOf()
// equivalent to: new Date().setUTCSeconds(30)
dayjs.utc().seconds()
// equivalent to: new Date().getUTCSeconds()Switch between UTC and local time:
dayjs#utc— convert to UTC modedayjs#local— convert to local time mode
---
Dayjs Clone
All Day.js objects are immutable. Use .clone() or pass an existing Day.js object to dayjs() to create a copy.
// Method 1: .clone()
var a = dayjs()
var b = a.clone()
// a and b are two separate Day.js objects
// Method 2: passing a Day.js object to dayjs()
var a = dayjs()
var b = dayjs(a)Both approaches produce independent objects that do not share references.
---
Validation — isValid()
Returns true if the Day.js object represents a valid date, false otherwise.
Non-Strict (default)
Checks whether the value can be parsed into a Date/Time object. Overflow dates are automatically adjusted.
dayjs('2022-01-33').isValid()
// true — parsed to 2022-02-02
dayjs('some invalid string').isValid()
// falseStrict
Validates that the value is both parseable and an actual calendar date. Requires the CustomParseFormat plugin.
dayjs('2022-02-31', 'YYYY-MM-DD', true).isValid()
// false — February 31st does not existPass true as the third parameter (or fourth when locale is specified) to enable strict mode.
Parse
| Name | Description | Path |
|---|---|---|
| Day.js — Parse | Day.js creates a wrapper around the native Date object by calling dayjs() with supported input formats. The Day.js object is immutable — all API operations that change it return a new instance. | parse.md |
Display Plugins
RelativeTime
Adds methods to format dates as human-readable relative time strings (e.g., "3 hours ago").
var relativeTime = require('dayjs/plugin/relativeTime')
// import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)API
dayjs().fromNow(withoutSuffix?) // "in 31 years"
dayjs().from(dayjs('1990-01-01')) // "in 31 years"
dayjs().from(dayjs('1990-01-01'), true) // "31 years" (no suffix)
dayjs().toNow(withoutSuffix?) // relative time to now
dayjs().to(dayjs('1990-01-01')) // "31 years ago"| Method | Returns | Description |
|---|---|---|
.fromNow(withoutSuffix?) | string | Relative time from now |
.from(compared, withoutSuffix?) | string | Relative time from a given date |
.toNow(withoutSuffix?) | string | Relative time to now |
.to(compared, withoutSuffix?) | string | Relative time to a given date |
---
Calendar
Returns a formatted string for calendar-style time display relative to a reference date.
var calendar = require('dayjs/plugin/calendar')
// import calendar from 'dayjs/plugin/calendar'
dayjs.extend(calendar)
dayjs().calendar(dayjs('2008-01-01'))Custom Formats
dayjs().calendar(null, {
sameDay: '[Today at] h:mm A',
nextDay: '[Tomorrow at] h:mm A',
nextWeek: 'dddd [at] h:mm A',
lastDay: '[Yesterday at] h:mm A',
lastWeek: '[Last] dddd [at] h:mm A',
sameElse: 'DD/MM/YYYY'
})| Key | When Used | Example Output |
|---|---|---|
sameDay | Same calendar day | "Today at 2:30 AM" |
nextDay | The next day | "Tomorrow at 2:30 AM" |
nextWeek | Within the next week | "Sunday at 2:30 AM" |
lastDay | The previous day | "Yesterday at 2:30 AM" |
lastWeek | Within the past week | "Last Monday at 2:30 AM" |
sameElse | All other dates | "17/10/2011" |
---
Duration
Adds dayjs.duration() and dayjs.isDuration() for working with time durations.
var duration = require('dayjs/plugin/duration')
// import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
dayjs.duration(100) // 100 milliseconds
dayjs.isDuration(value) // booleanSupports creating, cloning, humanizing, formatting, unit conversions (ms/s/m/h/d/w/M/y), add/subtract, diff, JSON, ISO 8601 strings, and locale.
---
ToArray
Adds .toArray() which returns a Day.js instance as an array of date/time components.
var toArray = require('dayjs/plugin/toArray')
// import toArray from 'dayjs/plugin/toArray'
dayjs.extend(toArray)
dayjs('2019-01-25').toArray()
// => [ 2019, 0, 25, 0, 0, 0, 0 ]
// year, month(0-indexed), date, hours, minutes, seconds, ms---
ToObject
Adds .toObject() which returns a Day.js instance as a plain object.
var toObject = require('dayjs/plugin/toObject')
// import toObject from 'dayjs/plugin/toObject'
dayjs.extend(toObject)
dayjs('2019-01-25').toObject()
// => { years: 2019, months: 0, date: 25, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }---
BadMutable
Makes Day.js instances mutable so setters mutate in place rather than returning a new instance. Not recommended — use only for moment.js migration.
var badMutable = require('dayjs/plugin/badMutable')
// import badMutable from 'dayjs/plugin/badMutable'
dayjs.extend(badMutable)
const today = dayjs()
today.add(1, 'day')
console.log(today) // mutated — shows tomorrowWithout this plugin, today.add(1, 'day') leaves today unchanged and returns a new instance.
Format Plugins
AdvancedFormat
Extends Day.js's format API with additional formatting tokens.
var advancedFormat = require('dayjs/plugin/advancedFormat')
// import advancedFormat from 'dayjs/plugin/advancedFormat'
dayjs.extend(advancedFormat)
dayjs().format('Q Do k kk X x')Additional Format Tokens
| Token | Output | Description |
|---|---|---|
Q | 1-4 | Quarter |
Do | 1st 2nd ... 31st | Day of Month with ordinal |
k | 1-24 | Hour beginning at 1 |
kk | 01-24 | Hour 2-digits beginning at 1 |
X | 1360013296 | Unix Timestamp in seconds |
x | 1360013296123 | Unix Timestamp in milliseconds |
w | 1 2 ... 52 53 | Week of year (requires WeekOfYear) |
ww | 01 02 ... 52 53 | Week of year 2-digits (requires WeekOfYear) |
W | 1 2 ... 52 53 | ISO Week of year (requires IsoWeek) |
WW | 01 02 ... 52 53 | ISO Week of year 2-digits (requires IsoWeek) |
wo | 1st 2nd ... 53rd | Week of year with ordinal (requires WeekOfYear) |
gggg | 2017 | Week Year (requires WeekYear) |
GGGG | 2017 | ISO Week Year (requires IsoWeek) |
z | EST | Abbreviated named offset (requires Timezone) |
zzz | Eastern Standard Time | Unabbreviated named offset (requires Timezone) |
---
LocalizedFormat
Extends format API to support locale-aware format tokens (e.g., L, LT, LLL).
var localizedFormat = require('dayjs/plugin/localizedFormat')
// import localizedFormat from 'dayjs/plugin/localizedFormat'
dayjs.extend(localizedFormat)
dayjs().format('L LT')For the full list of localized format tokens, refer to the display/format localized formats reference.
---
CustomParseFormat
Extends the dayjs() constructor to parse custom date string formats.
var customParseFormat = require('dayjs/plugin/customParseFormat')
// import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)Usage
// Custom format
dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z')
// => 1969-05-02T18:02:03.000Z
// Locale-specific parsing
dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es')
// => 2018-01-15T00:00:00.000Z
// Strict mode
dayjs('1970-00-00', 'YYYY-MM-DD', true)Parameters
| Parameter | Type | Description |
|---|---|---|
| date string | string | Input date string to parse |
| format | string | Format token string describing the input |
| locale | string | (optional) Locale for month/weekday name parsing |
| strict | boolean | (optional) Reject invalid dates when true |
Get/Set Plugins
DayOfYear
Gets or sets the day of the year (1–365/366).
var dayOfYear = require('dayjs/plugin/dayOfYear')
// import dayOfYear from 'dayjs/plugin/dayOfYear'
dayjs.extend(dayOfYear)
dayjs('2010-01-01').dayOfYear() // 1 (get)
dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 (set)---
WeekOfYear
Gets or sets the week number of the year.
var weekOfYear = require('dayjs/plugin/weekOfYear')
// import weekOfYear from 'dayjs/plugin/weekOfYear'
dayjs.extend(weekOfYear)
dayjs('2018-06-27').week() // 26 (get)
dayjs('2018-06-27').week(5) // set week 5---
WeekYear
Gets the locale-aware week year. Requires WeekOfYear plugin (extend first).
var weekOfYear = require('dayjs/plugin/weekOfYear')
var weekYear = require('dayjs/plugin/weekYear')
// import weekOfYear from 'dayjs/plugin/weekOfYear'
// import weekYear from 'dayjs/plugin/weekYear'
dayjs.extend(weekOfYear)
dayjs.extend(weekYear)
dayjs().weekYear()---
IsoWeek
Gets/sets ISO week number, ISO weekday, and ISO week year. Also extends .startOf() / .endOf() with 'isoWeek' unit.
var isoWeek = require('dayjs/plugin/isoWeek')
// import isoWeek from 'dayjs/plugin/isoWeek'
dayjs.extend(isoWeek)
dayjs().isoWeek() // get ISO week number
dayjs().isoWeekday() // get ISO weekday (1=Mon, 7=Sun)
dayjs().isoWeekYear() // get ISO week year
dayjs().startOf('isoWeek')
dayjs().endOf('isoWeek')---
IsoWeeksInYear
Returns the number of ISO weeks in a year. Requires IsLeapYear plugin.
var isoWeeksInYear = require('dayjs/plugin/isoWeeksInYear')
var isLeapYear = require('dayjs/plugin/isLeapYear')
// import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear'
// import isLeapYear from 'dayjs/plugin/isLeapYear'
dayjs.extend(isoWeeksInYear)
dayjs.extend(isLeapYear)
dayjs('2004-01-01').isoWeeksInYear() // 53
dayjs('2005-01-01').isoWeeksInYear() // 52---
QuarterOfYear
Gets or sets the quarter (1–4). Extends .add(), .subtract(), .startOf(), .endOf() with 'quarter' unit.
var quarterOfYear = require('dayjs/plugin/quarterOfYear')
// import quarterOfYear from 'dayjs/plugin/quarterOfYear'
dayjs.extend(quarterOfYear)
dayjs('2010-04-01').quarter() // 2 (get)
dayjs('2010-04-01').quarter(2) // set quarter 2---
Weekday
Gets or sets the locale-aware day of the week. The start of the week (Sunday or Monday) is determined by the current locale.
var weekday = require('dayjs/plugin/weekday')
// import weekday from 'dayjs/plugin/weekday'
dayjs.extend(weekday)
// When Sunday starts the week:
dayjs().weekday(-7) // last Sunday
dayjs().weekday(7) // next Sunday
// When Monday starts the week:
dayjs().weekday(-7) // last Monday
dayjs().weekday(7) // next Monday---
PluralGetSet
Adds plural aliases for all getter/setter methods.
var pluralGetSet = require('dayjs/plugin/pluralGetSet')
// import pluralGetSet from 'dayjs/plugin/pluralGetSet'
dayjs.extend(pluralGetSet)
dayjs().milliseconds() // same as dayjs().millisecond()
dayjs().seconds()
dayjs().minutes()
dayjs().hours()
dayjs().days()
dayjs().weeks()
dayjs().isoWeeks()
dayjs().months()
dayjs().quarters()
dayjs().years()
dayjs().dates()---
MinMax
Adds dayjs.max() and dayjs.min() static methods to compare multiple Day.js instances.
var minMax = require('dayjs/plugin/minMax')
// import minMax from 'dayjs/plugin/minMax'
dayjs.extend(minMax)
// Returns the latest date (multiple arguments)
dayjs.max(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'))
// Returns the earliest date (array argument)
dayjs.min([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])Both methods return a Day.js object.
Other Plugins
BuddhistEra
Extends format() to support Buddhist Era (B.E.) year tokens. The Buddhist Era year = Gregorian year + 543 (e.g., 1977 AD = 2520 BE). Used in Cambodia, Laos, Myanmar, Thailand, Sri Lanka, and some Chinese communities.
var buddhistEra = require('dayjs/plugin/buddhistEra')
// import buddhistEra from 'dayjs/plugin/buddhistEra'
dayjs.extend(buddhistEra)
dayjs().format('BBBB BB')Format Tokens
| Token | Output Example | Description |
|---|---|---|
BBBB | 2561 | Full Buddhist Era year (Gregorian + 543) |
BB | 61 | Two-digit Buddhist Era year |
---
DevHelper
Provides development-time warnings and hints. Automatically disabled when process.env.NODE_ENV === 'production'.
var devHelper = require('dayjs/plugin/devHelper')
// import devHelper from 'dayjs/plugin/devHelper'
dayjs.extend(devHelper)Conditional Loading (Recommended Pattern)
if (isInDevelopment) {
var devHelper = require('dayjs/plugin/devHelper')
dayjs.extend(devHelper)
}JavaScript minifiers (e.g., UglifyJS) can automatically strip this plugin from production bundles.
---
LocaleData
Adds dayjs.localeData() API to access locale-specific information such as month names, weekday names, and format patterns.
var localeData = require('dayjs/plugin/localeData')
// import localeData from 'dayjs/plugin/localeData'
dayjs.extend(localeData)Global Methods
dayjs.months()
dayjs.monthsShort()
dayjs.weekdays()
dayjs.weekdaysShort()
dayjs.weekdaysMin()
dayjs.longDateFormat('L')Global Locale Data Object
const globalLocaleData = dayjs.localeData()
globalLocaleData.firstDayOfWeek()
globalLocaleData.months()
globalLocaleData.monthsShort()
globalLocaleData.weekdays()
globalLocaleData.weekdaysShort()
globalLocaleData.weekdaysMin()
globalLocaleData.longDateFormat('L')
globalLocaleData.months(dayjs())
globalLocaleData.monthsShort(dayjs())
globalLocaleData.weekdays(dayjs())
globalLocaleData.weekdaysShort(dayjs())
globalLocaleData.weekdaysMin(dayjs())
globalLocaleData.meridiem()
globalLocaleData.ordinal()Instance Locale Data Object
const instanceLocaleData = dayjs().localeData()
instanceLocaleData.firstDayOfWeek()
instanceLocaleData.months()
instanceLocaleData.monthsShort()
instanceLocaleData.weekdays()
instanceLocaleData.weekdaysShort()
instanceLocaleData.weekdaysMin()
instanceLocaleData.longDateFormat('L')
instanceLocaleData.meridiem()
instanceLocaleData.ordinal()To use longDateFormat('L'), also extend localizedFormat:
import localizedFormat from 'dayjs/plugin/localizedFormat'
dayjs.extend(localizedFormat)---
UpdateLocale
Adds dayjs.updateLocale() to dynamically modify locale properties.
var updateLocale = require('dayjs/plugin/updateLocale')
// import updateLocale from 'dayjs/plugin/updateLocale'
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
months: String[]
})| Parameter | Type | Description |
|---|---|---|
| locale | string | Target locale identifier (e.g., 'en') |
| config | object | Locale properties to update (e.g., months as string array) |
Parse Plugins
ArraySupport
Extends dayjs() and dayjs.utc to accept an array argument.
var arraySupport = require('dayjs/plugin/arraySupport')
// import arraySupport from 'dayjs/plugin/arraySupport'
dayjs.extend(arraySupport)
// [year, month, day, hour, minute, second, millisecond]
dayjs([2010, 1, 14, 15, 25, 50, 125])
dayjs.utc([2010, 1, 14, 15, 25, 50, 125])---
ObjectSupport
Extends dayjs(), dayjs.utc, dayjs().set, dayjs().add, and dayjs().subtract to accept object arguments.
var objectSupport = require('dayjs/plugin/objectSupport')
// import objectSupport from 'dayjs/plugin/objectSupport'
dayjs.extend(objectSupport)
// Constructor
dayjs({ year: 2010, month: 1, day: 12 })
dayjs.utc({ year: 2010, month: 1, day: 12 })
// Setter
dayjs().set({ year: 2010, month: 1, day: 12 })
// Add / Subtract
dayjs().add({ M: 1 })
dayjs().subtract({ month: 1 })---
BigIntSupport
Extends dayjs() and dayjs.unix() to accept BigInt arguments.
var bigIntSupport = require('dayjs/plugin/bigIntSupport')
// import bigIntSupport from 'dayjs/plugin/bigIntSupport'
dayjs.extend(bigIntSupport)
// BigInt milliseconds
dayjs(BigInt(1666310421101))
// BigInt Unix seconds
dayjs.unix(BigInt(1666311003))---
PreParsePostFormat
Allows locale definitions to pre-process input strings before parsing and post-process output strings after formatting. Mirrors moment.js locale behavior.
Requirements: The localeData plugin must be loaded before this plugin. Also affects the RelativeTime plugin by design.
import dayjs from 'dayjs'
import preParsePostFormat from 'dayjs/plugin/preParsePostFormat'
dayjs.extend(preParsePostFormat)
// Arabic locale example
const symbolMap = {
1: '١', 2: '٢', 3: '٣', 4: '٤', 5: '٥',
6: '٦', 7: '٧', 8: '٨', 9: '٩', 0: '٠'
}
const numberMap = {
'١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5',
'٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0'
}
const locale = {
name: 'ar',
preparse(string) {
return string
.replace(/[١٢٣٤٥٦٧٨٩٠]/g, match => numberMap[match])
.replace(/،/g, ',')
},
postformat(string) {
return string
.replace(/\d/g, match => symbolMap[match])
.replace(/,/g, '،')
}
}preparse converts locale-specific input (e.g., Arabic numerals) to standard form before parsing. postformat converts output back to locale-specific form for display.
Plugin Overview
Day.js ships without plugins by default. Plugins are independent modules that extend Day.js functionality and can be loaded selectively.
Plugin Architecture
A plugin is a function that receives three parameters:
export default (option, dayjsClass, dayjsFactory) => {
// Extend dayjs() instances
dayjsClass.prototype.isSameOrBefore = function(arguments) {}
// Extend dayjs static methods
dayjsFactory.utc = arguments => {}
// Override existing APIs
const oldFormat = dayjsClass.prototype.format
dayjsClass.prototype.format = function(arguments) {
const result = oldFormat.bind(this)(arguments)
// return modified result
}
}| Parameter | Description |
|---|---|
option | Configuration settings passed to the plugin |
dayjsClass | The Day.js class — use for prototype extensions |
dayjsFactory | The Day.js factory function — use for static method additions |
Loading in Node.js
// CommonJS
var AdvancedFormat = require('dayjs/plugin/advancedFormat')
dayjs.extend(AdvancedFormat)
// ES 2015
import AdvancedFormat from 'dayjs/plugin/advancedFormat'
dayjs.extend(AdvancedFormat)Loading in the Browser
From local path
<script src="path/to/dayjs/plugin/advancedFormat"></script>
<script>
dayjs.extend(window.dayjs_plugin_advancedFormat)
</script>From CDN (jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
<script>dayjs.extend(window.dayjs_plugin_utc)</script>Browser plugins are exposed as window.dayjs_plugin_[PLUGINNAME]. The script must be loaded before calling dayjs.extend().
Query Plugins
IsBetween
Returns a boolean indicating if a date falls between two other dates.
var isBetween = require('dayjs/plugin/isBetween')
// import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)API
dayjs(date).isBetween(start, end, granularity?, inclusivity?)Parameters
| Parameter | Type | Description |
|---|---|---|
start | Dayjs / string | Start date boundary |
end | Dayjs / string | End date boundary |
granularity | string | (optional) Precision: 'year', 'month', 'day', etc. |
inclusivity | string | (optional) Boundary inclusion: '()', '[]', '[)', '(]' |
Inclusivity Options
| Value | Meaning |
|---|---|
'()' | Exclude both start and end (default) |
'[]' | Include both start and end |
'[)' | Include start, exclude end |
'(]' | Exclude start, include end |
Examples
dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year')
dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', 'day', '[)')---
IsLeapYear
Returns a boolean indicating whether the year is a leap year.
var isLeapYear = require('dayjs/plugin/isLeapYear')
// import isLeapYear from 'dayjs/plugin/isLeapYear'
dayjs.extend(isLeapYear)
dayjs('2000-01-01').isLeapYear() // true---
IsSameOrAfter
Returns a boolean indicating if a date is the same as or after another date.
var isSameOrAfter = require('dayjs/plugin/isSameOrAfter')
// import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrAfter)
dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year')| Parameter | Type | Description |
|---|---|---|
| date | Dayjs / string | Date to compare against |
| unit | string | (optional) Unit of time for comparison granularity |
---
IsSameOrBefore
Returns a boolean indicating if a date is the same as or before another date.
var isSameOrBefore = require('dayjs/plugin/isSameOrBefore')
// import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
dayjs.extend(isSameOrBefore)
dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year')| Parameter | Type | Description |
|---|---|---|
| date | Dayjs / string | Date to compare against |
| unit | string | (optional) Unit of time for comparison granularity |
---
IsToday
Returns a boolean indicating whether the Day.js object is today.
var isToday = require('dayjs/plugin/isToday')
// import isToday from 'dayjs/plugin/isToday'
dayjs.extend(isToday)
dayjs().isToday() // true---
IsTomorrow
Returns a boolean indicating whether the Day.js object is tomorrow.
var isTomorrow = require('dayjs/plugin/isTomorrow')
// import isTomorrow from 'dayjs/plugin/isTomorrow'
dayjs.extend(isTomorrow)
dayjs().add(1, 'day').isTomorrow() // true---
IsYesterday
Returns a boolean indicating whether the Day.js object is yesterday.
var isYesterday = require('dayjs/plugin/isYesterday')
// import isYesterday from 'dayjs/plugin/isYesterday'
dayjs.extend(isYesterday)
dayjs().add(-1, 'day').isYesterday() // truePlugin
| Name | Description | Path |
|---|---|---|
| Display Plugins | Adds methods to format dates as human-readable relative time… | ./display-plugins.md |
| Format Plugins | Extends Day.js's format API with additional formatting tokens… | ./format-plugins.md |
| Get/Set Plugins | Gets or sets the day of the year (1–365/366)… | ./getset-plugins.md |
| Other Plugins | Extends format() to support Buddhist Era (B.E.) year tokens… | ./other-plugins.md |
| Parse Plugins | Extends dayjs() and dayjs.utc to accept an array argument… | ./parse-plugins.md |
| Plugin Overview | Day.js ships without plugins by default. Plugins are… | ./plugin-overview.md |
| Query Plugins | Returns a boolean indicating if a date falls between two… | ./query-plugins.md |
| Timezone/UTC Plugins | Adds UTC mode with .utc(), .local(), .utcOffset(), and… | ./timezone-utc-plugins.md |
Timezone/UTC Plugins
UTC
Adds UTC mode with .utc(), .local(), .utcOffset(), and .isUTC() methods.
var utc = require('dayjs/plugin/utc')
// import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)API
// Create in UTC mode
dayjs.utc().format() // 2019-03-06T09:11:55Z
// Convert local to UTC
dayjs().utc().format() // 2019-03-06T09:11:55Z
// Check UTC mode
dayjs.utc().isUTC() // true
// Switch back to local time
dayjs.utc().local().format() // 2019-03-06T17:11:55+08:00
// With CustomParseFormat
dayjs.utc('2018-01-01', 'YYYY-MM-DD')
// UTC offset
dayjs().utcOffset()| Method | Signature | Returns | Description |
|---|---|---|---|
dayjs.utc | (dateType?, format?) | Dayjs | Create a Dayjs in UTC mode |
.utc() | () | Dayjs | Clone with UTC flag |
.local() | () | Dayjs | Clone in local time |
.utcOffset() | () | Dayjs | Clone with new UTC offset |
.isUTC() | () | boolean | Whether instance is in UTC mode |
Notes
In UTC mode, display methods output UTC time. Getters/setters use Date#getUTC* / Date#setUTC* internally.
---
Timezone
Adds timezone conversion with dayjs.tz(), .tz(), dayjs.tz.guess(), and dayjs.tz.setDefault(). Requires UTC plugin.
var utc = require('dayjs/plugin/utc')
var timezone = require('dayjs/plugin/timezone')
// import utc from 'dayjs/plugin/utc'
// import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)Converting Between Timezones
// Treat existing timestamp as UTC, then display in target timezone
dayjs('2014-06-01 12:00').tz('America/New_York')
// => 2014-06-01T08:00:00 in America/New_York
// Keep the wall-clock time, change timezone label
dayjs('2014-06-01 12:00').tz('America/New_York', true)
// => 2014-06-01T12:00:00 in America/New_YorkParsing in a Timezone
dayjs.tz('2013-11-18 11:55', 'Asia/Taipei').format()
// => 2013-11-18T11:55:00+08:00Converting UTC to Timezone
dayjs.utc('2013-11-18 11:55').tz('Asia/Taipei').format()
// => 2013-11-18T19:55:00+08:00Guess User Timezone
dayjs.tz.guess() // e.g., "America/Chicago"Default Timezone
dayjs.tz.setDefault('America/New_York') // set default
dayjs.tz.setDefault() // reset to system timezoneNotes
Unlike Moment.js, dayjs() always defaults to local timezone even after setDefault(). Only dayjs.tz() uses the configured default timezone.
Day.js — Query
There are several methods to query a Day.js object. These methods allow you to compare dates, check date relationships, and validate Day.js instances.
---
Query (Overview)
The Query section covers the following methods:
- Is Before — Compare if a date is before another
- Is Same — Check if dates are identical
- Is After — Determine if a date is after another
- Is Same or Before — Combined comparison check (plugin)
- Is Same or After — Combined comparison check (plugin)
- Is Between — Verify if a date falls within a range (plugin)
- Is a Dayjs — Validate if a variable is a Day.js instance
- Is Leap Year — Check leap year status (plugin)
---
Is Before
This indicates whether the Day.js object is before the other supplied date-time.
Signature
dayjs().isBefore(date, unit?)Usage
dayjs().isBefore(dayjs('2011-01-01')) // default millisecondsWith Granularity
To limit comparison to a specific unit rather than milliseconds, pass a unit as the second parameter. The comparison respects that unit and all units above it in the hierarchy.
dayjs().isBefore('2011-01-01', 'month') // compares month and yearNotes
- Units are case-insensitive
- Units support both plural and short forms (e.g.
year/years/y) - Available units: see List of all available units
---
Is Same
This indicates whether the Day.js object is the same as the other supplied date-time.
Signature
dayjs().isSame(date, unit?)Usage
dayjs().isSame(dayjs('2011-01-01')) // default millisecondsWith Granularity
When a unit is specified, the method matches all units equal to or larger than the specified unit.
dayjs().isSame('2011-01-01', 'year')- Specifying
monthchecks both month and year - Specifying
daychecks day, month, and year
Notes
- Units are case-insensitive
- Units support both plural and abbreviated forms
- Available units: see List of all available units
---
Is After
This indicates whether the Day.js object is after the other supplied date-time.
Signature
dayjs().isAfter(date, unit?)Usage
dayjs().isAfter(dayjs('2011-01-01')) // default millisecondsWith Granularity
To compare dates at a specific unit level rather than milliseconds, pass a unit as the second parameter. The comparison respects that unit and all units above it in the hierarchy.
dayjs().isAfter('2011-01-01', 'month') // compares month and yearNotes
- Units are case-insensitive
- Units support both plural and short forms
- Available units: see List of all available units
---
Is Same or Before
This indicates whether the Day.js object is the same as or before another supplied date-time.
Requires the `IsSameOrBefore` plugin.
Setup
dayjs.extend(isSameOrBefore)Signature
dayjs().isSameOrBefore(date, unit?)Usage
dayjs.extend(isSameOrBefore)
dayjs().isSameOrBefore(dayjs('2011-01-01')) // default millisecondsWith Granularity
dayjs().isSameOrBefore('2011-01-01', 'year')Notes
- Units are case-insensitive and support both plural and abbreviated forms
- Available units: see List of all available units
---
Is Same or After
This indicates whether the Day.js object is the same as or after another supplied date-time.
Requires the `IsSameOrAfter` plugin.
Setup
dayjs.extend(isSameOrAfter)Signature
dayjs().isSameOrAfter(date, unit?)Usage
dayjs.extend(isSameOrAfter)
dayjs().isSameOrAfter(dayjs('2011-01-01')) // default millisecondsWith Granularity
dayjs().isSameOrAfter('2011-01-01', 'year')Notes
- Units are case-insensitive and support both plural and short form variations
- Available units: see List of all available units
---
Is Between
This indicates whether the Day.js object is between two other supplied date-times.
Requires the `IsBetween` plugin.
Setup
dayjs.extend(isBetween)Signature
dayjs().isBetween(dateA, dateB, unit?, inclusivity?)Parameters
| Parameter | Type | Description |
|---|---|---|
| dateA | string \ | Dayjs |
| dateB | string \ | Dayjs |
| unit | string (optional) | Granularity level for comparison |
| inclusivity | string (optional) | Bracket notation for boundary inclusion ('()', '[)', '(]', '[]') |
Usage
dayjs.extend(isBetween)
dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'))
// default millisecondsWith Unit
To limit comparison granularity, specify a unit as the third argument. The comparison respects the given unit and all units above it.
dayjs().isBetween('2010-10-19', '2010-10-25', 'month') // compares month and yearInclusivity
The fourth parameter uses bracket notation to define boundary inclusion:
[— include the boundary value(— exclude the boundary value
Both start and end indicators must be provided together.
dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)')
// true — start inclusive, end exclusive| Notation | Meaning |
|---|---|
'()' | Exclude both start and end (default) |
'[)' | Include start, exclude end |
'(]' | Exclude start, include end |
'[]' | Include both start and end |
Notes
- Units are case-insensitive and support plural and abbreviated forms
- Available units: see List of all available units
---
Is a Dayjs
This indicates whether a variable is a Day.js object or not.
Signature
dayjs.isDayjs(d)Usage
dayjs.isDayjs(dayjs()) // true
dayjs.isDayjs(new Date()) // falseAlternative: instanceof
The instanceof operator provides equivalent functionality:
dayjs() instanceof dayjs // true---
Is Leap Year
This indicates whether the Day.js object's year is a leap year or not.
Requires the `IsLeapYear` plugin.
Setup
dayjs.extend(isLeapYear)Signature
dayjs().isLeapYear()Usage
dayjs.extend(isLeapYear)
dayjs('2000-01-01').isLeapYear() // true
dayjs('2001-01-01').isLeapYear() // falseNotes
- Returns a boolean:
truefor leap years,falseotherwise - Must call
dayjs.extend(isLeapYear)before using this method
Query
| Name | Description | Path |
|---|---|---|
| Day.js — Query | There are several methods to query a Day.js object. These methods allow… | query.md |
timezone
| Name | Description | Path |
|---|---|---|
| Time Zone | Day.js provides time zone support through the Internationalization API in supported environments. This approach eliminates the need to bundle extra timezone data. | timezone.md |
Time Zone
Day.js provides time zone support through the Internationalization API in supported environments. This approach eliminates the need to bundle extra timezone data.
Requirement: The Timezone plugin must be extended. Available time zone names are listed in the IANA database. For unsupported environments, a polyfill is recommended.
Setup
dayjs.extend(utc)
dayjs.extend(timezone)Parsing in Zone
Parse a date-time string within a specified timezone and obtain a Day.js object instance.
dayjs.tz("2013-11-18T11:55:20", "America/Toronto") // '2013-11-18T11:55:20-05:00'Parsing with Format
If you know the input string's format, pass it as the second argument. Requires the `CustomParseFormat` plugin.
dayjs.extend(customParseFormat)
dayjs.tz("12-25-1995", "MM-DD-YYYY", "America/Toronto")Converting to Zone
Change the time zone, update the offset, and return a Day.js object instance.
// Assumes execution in 'Europe/Berlin' timezone (UTC+01:00)
dayjs("2013-11-18T11:55:20") // '2013-11-18T11:55:20+01:00'
dayjs("2013-11-18T11:55:20").tz("America/Toronto") // '2013-11-18T05:55:20-05:00'Preserving Local Time
Pass true as the second argument to keep the local time display and only update the timezone offset.
dayjs("2013-11-18T11:55:20").tz("America/Toronto", true) // '2013-11-18T11:55:20-05:00'| Parameter | Type | Description |
|---|---|---|
| timezone | string | Target timezone identifier (e.g., "America/Toronto") |
| keepLocalTime | boolean | When true, preserves the local time and updates only the offset. Default: false |
Guessing User Timezone
Return the user's time zone as a string.
dayjs.tz.guess() // e.g. "America/Chicago"Set Default Timezone
Change the default timezone from the local timezone to a custom one.
dayjs.tz.setDefault("America/New_York")
dayjs.tz("2014-06-01 12:00") // 2014-06-01T12:00:00-04:00 (uses default)
dayjs.tz("2014-06-01 12:00", "Asia/Tokyo") // 2014-06-01T12:00:00+09:00 (overrides default)
dayjs.tz.setDefault() // Reset to local timezoneNote: dayjs.tz.setDefault does not affect existing Day.js objects created before the call. Only newly created instances use the updated default.
Add and Subtract
Shift a date forward or backward by a given amount and unit.
import dayjs from 'dayjs'
const base = dayjs('2019-01-25')
// Add
base.add(7, 'day') // => 2019-02-01
base.add(1, 'month') // => 2019-02-25
base.add(1, 'year') // => 2020-01-25
// Subtract
base.subtract(7, 'day') // => 2019-01-18
base.subtract(1, 'month') // => 2018-12-25
// Chaining
dayjs('2019-01-25')
.add(1, 'day')
.subtract(1, 'year')
.format('YYYY-MM-DD')
// => '2018-01-26'
// Short-form unit aliases
base.add(7, 'd') // 'day'
base.add(2, 'w') // weeks
base.add(3, 'M') // months (capital M)
base.add(1, 'y') // yearsNotes
addandsubtractalways return a new Day.js object; the original is unchanged.- Unit strings are case-insensitive and support plural forms (
days,months). M(month) is capital;m(minute) is lowercase — mixing them up is a common mistake.- Chaining is supported because each operation returns a Dayjs instance.
Basic Parsing
Create Day.js objects from strings, native Date, timestamps, and objects.
import dayjs from 'dayjs'
// Current time
dayjs() // => Dayjs object for now
// ISO 8601 string
dayjs('2019-01-25') // => 2019-01-25T00:00:00
// Native Date
dayjs(new Date(2019, 0, 25)) // => 2019-01-25T00:00:00
// Unix timestamp (milliseconds)
dayjs(1548381600000)
// Unix timestamp (seconds) — requires unix()
dayjs.unix(1548381600)
// Object
dayjs({ year: 2019, month: 0, date: 25 }) // month is 0-indexed
// Clone
const a = dayjs('2019-01-25')
const b = dayjs(a) // independent copyNotes
- Day.js objects are immutable; every operation returns a new instance.
- Month in object notation is 0-indexed (0 = January), matching native
Date. dayjs.unix()expects seconds, not milliseconds.- Invalid input results in an object where
.isValid()returnsfalse.
Date Comparison
Compare two dates using isBefore, isAfter, isSame, and diff.
import dayjs from 'dayjs'
const a = dayjs('2019-01-25')
const b = dayjs('2018-06-05')
// Boolean comparisons
a.isBefore(b) // false
a.isAfter(b) // true
a.isSame(b) // false
a.isSame('2019-01-25') // true
// Granularity — only compare down to specified unit
a.isBefore('2019-02-01', 'month') // false (same month? no, but Jan < Feb → true)
a.isSame('2019-06-15', 'year') // true (both 2019)
// diff — numeric difference between two dates
a.diff(b) // 20214000000 (milliseconds, default)
a.diff(b, 'month') // 7
a.diff(b, 'month', true) // 7.645161... (float)
a.diff(b, 'day') // 234Notes
isBefore/isAfter/isSameaccept a Dayjs object or any string/Date dayjs can parse.- The optional second argument sets comparison granularity; coarser units ignore finer-grained differences.
diffreturns a truncated integer by default; passtrueas the third argument for a float.- Negative
diffmeans the argument is later than the caller.
Custom Format Parsing
Parse date strings that don't follow ISO 8601 using the CustomParseFormat plugin.
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)
// Parse with explicit format
dayjs('12-25-1995', 'MM-DD-YYYY') // => 1995-12-25
// Locale-aware parsing
import 'dayjs/locale/es'
dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') // => 2018-01-15
// Strict mode — rejects invalid dates
dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false
// Multiple candidate formats
dayjs('12-25-2001', ['YYYY', 'YYYY-MM-DD'])Notes
- Without
customParseFormat, non-ISO strings may be parsed incorrectly or produce invalid objects. - Strict mode (
trueas third or fourth argument) requires an exact format match. - Locale argument must come before the strict flag:
dayjs(str, format, locale, strict). - Common tokens:
YYYYyear,MMmonth,DDday,HH/mm/sstime,AAM/PM.
Duration
Represent and manipulate lengths of time (not tied to a specific start point) using the Duration plugin.
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import relativeTime from 'dayjs/plugin/relativeTime' // needed for humanize()
dayjs.extend(duration)
dayjs.extend(relativeTime)
// Create from milliseconds
dayjs.duration(1000) // 1 second
// Create from a value + unit
dayjs.duration(2, 'days')
dayjs.duration(90, 'minutes')
// Create from an object
dayjs.duration({ hours: 2, minutes: 30, seconds: 15 })
// Create from ISO 8601 duration string
dayjs.duration('P1Y2M3DT4H5M6S') // 1y 2mo 3d 4h 5m 6s
// Access components
const d = dayjs.duration({ hours: 1, minutes: 30 })
d.hours() // 1
d.minutes() // 30
d.asMinutes() // 90 (total as a single unit)
d.asMilliseconds() // 5400000
// Human-readable string (requires relativeTime plugin)
dayjs.duration(1, 'day').humanize() // "a day"
dayjs.duration(3, 'months').humanize() // "3 months"
// Check type
dayjs.isDuration(d) // trueNotes
- Duration is a stand-alone concept: it has no reference date (use
add/subtractto apply it to one). hours()returns the hours component only;asHours()converts the entire duration.humanize()requires the RelativeTime plugin to be loaded first.- ISO 8601 strings:
Pprefix,Tseparates date from time parts (P1DT2H= 1 day 2 hours).
Formatting
Convert a Day.js object to a formatted string using format tokens.
import dayjs from 'dayjs'
// Default ISO 8601
dayjs().format()
// => '2020-04-02T08:02:17-05:00'
// Custom tokens
dayjs('2019-01-25').format('DD/MM/YYYY') // => '25/01/2019'
dayjs('2019-01-25').format('YYYY-MM-DD') // => '2019-01-25'
dayjs('2019-01-25').format('h:mm A') // => '12:00 AM'
dayjs('2019-01-25').format('dddd, MMMM D') // => 'Friday, January 25'
// Escape literal text with square brackets
dayjs('2019-01-25').format('[Today is] dddd') // => 'Today is Friday'Notes
YYYY= 4-digit year,MM= 2-digit month,DD= 2-digit day.HH= 24-hour clock,hh= 12-hour clock; pairhhwithA(AM/PM).dddd= full weekday name;ddd= abbreviated.- Wrap any literal text in
[ ]to prevent token substitution.
Locale (i18n)
Switch the display language globally or per-instance.
import dayjs from 'dayjs'
import 'dayjs/locale/ja'
import 'dayjs/locale/de'
// Change globally
dayjs.locale('ja')
dayjs('2019-01-25').format('YYYY年MM月DD日(dddd)') // => '2019年01月25日(金曜日)'
// Revert to English
dayjs.locale('en')
// Per-instance locale (does not affect global)
dayjs('2019-01-25').locale('de').format('dddd, D. MMMM YYYY')
// => 'Freitag, 25. Januar 2019'
// With RelativeTime in locale
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)
dayjs.locale('ja')
dayjs('2020-01-01').fromNow() // => '5年前'Notes
- Only English is bundled by default; each additional locale must be explicitly imported.
- Changing the global locale does not retroactively affect already-created instances.
- Per-instance locale via
.locale('xx')returns a new object and leaves the global setting untouched. - Locale names match the IETF BCP 47 subtags used in the
dayjs/locale/directory (e.g.,ja,zh-cn,pt-br).
samples
| Name | Description | Path |
|---|---|---|
| Add and Subtract | Shift a date forward or backward by a given amount and unit. | add-subtract.md |
| Basic Parsing | Create Day.js objects from strings, native Date, timestamps, and objects. | basic-parsing.md |
| Date Comparison | Compare two dates using isBefore, isAfter, isSame, and diff. | comparison.md |
| Custom Format Parsing | Parse date strings that don't follow ISO 8601 using the CustomParseFormat plugin. | custom-format-parsing.md |
| Duration | Represent and manipulate lengths of time (not tied to a specific start point) using the Duration plugin. | duration.md |
| Formatting | Convert a Day.js object to a formatted string using format tokens. | formatting.md |
| Locale (i18n) | Switch the display language globally or per-instance. | locale.md |
| Relative Time | Display human-readable relative time strings such as "3 days ago" using the RelativeTime plugin. | relative-time.md |
| Start and End of Time Unit | Snap a date to the beginning or end of a given time unit. | start-end-of.md |
| Timezone | Parse and convert dates across timezones using the UTC and Timezone plugins. | timezone.md |
Relative Time
Display human-readable relative time strings such as "3 days ago" using the RelativeTime plugin.
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)
// From now
dayjs().fromNow() // "a few seconds ago"
dayjs('2020-01-01').fromNow() // "5 years ago"
dayjs('2099-01-01').fromNow() // "in 73 years"
// Without the suffix/prefix
dayjs('2020-01-01').fromNow(true) // "5 years"
// Relative to a specific date
dayjs('2025-01-01').from(dayjs('2024-01-01')) // "in a year"
dayjs('2025-01-01').from(dayjs('2024-01-01'), true) // "a year"
// To now / to a specific date
dayjs('2020-01-01').toNow() // "in 5 years" (opposite direction)
dayjs('2020-01-01').to(dayjs('2025-06-01')) // "in 5 years"Notes
- RelativeTime depends on locale; load a locale before calling these methods to get localized strings.
fromNow()is shorthand for.from(dayjs()).toNow()is shorthand for.to(dayjs())and reverses the direction.withoutSuffix: truestrips "ago" / "in" for use in custom sentence construction.
Start and End of Time Unit
Snap a date to the beginning or end of a given time unit.
import dayjs from 'dayjs'
const d = dayjs('2019-04-15 12:30:45')
// Start of unit
d.startOf('year') // => 2019-01-01 00:00:00
d.startOf('month') // => 2019-04-01 00:00:00
d.startOf('week') // => 2019-04-14 00:00:00 (Sunday by default)
d.startOf('day') // => 2019-04-15 00:00:00
d.startOf('hour') // => 2019-04-15 12:00:00
// End of unit
d.endOf('year') // => 2019-12-31 23:59:59.999
d.endOf('month') // => 2019-04-30 23:59:59.999
d.endOf('day') // => 2019-04-15 23:59:59.999
// Practical: date range for current month
const from = dayjs().startOf('month')
const to = dayjs().endOf('month')Notes
- Both methods return a cloned object; the original is unchanged.
- Week start day depends on locale; use
weekdayplugin for locale-aware week boundaries. endOfsets milliseconds to 999, making it safe for inclusive range queries.- Units are case-insensitive and accept plural/short forms (
'days','d').
Timezone
Parse and convert dates across timezones using the UTC and Timezone plugins.
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)
// Parse a string in a specific timezone
dayjs.tz('2013-11-18 11:55', 'Asia/Taipei').format()
// => '2013-11-18T11:55:00+08:00'
// Convert an existing time to another timezone
dayjs('2014-06-01 12:00').tz('America/New_York').format()
// => '2014-06-01T08:00:00-04:00'
// Detect the user's local timezone
dayjs.tz.guess() // => 'Asia/Tokyo' (example)
// Set a default timezone for the app
dayjs.tz.setDefault('America/New_York')
dayjs.tz.setDefault() // reset to system timezoneNotes
- Both
utcandtimezoneplugins must be loaded;timezonedepends onutc. dayjs.tz(str, tz)interprets the string as local time in that timezone..tz(tz)on an existing instance converts to the target timezone without changing the underlying instant.- Timezone names follow the IANA database (e.g.,
'America/New_York','Asia/Tokyo').
Customization
カスタムロケールの作成と既存ロケールの更新。
カスタムロケールの作成
var localeObject = { /* ロケールオブジェクト */ }
dayjs.locale('en-my-settings', localeObject)既存ロケールの更新(UpdateLocale プラグイン必須)
import updateLocale from 'dayjs/plugin/updateLocale'
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
months: [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
]
})月の省略形を更新
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
monthsShort: [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
})曜日名を更新
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
weekdays: [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
})相対時刻の文字列を更新
dayjs.extend(updateLocale)
dayjs.updateLocale('en', {
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years'
}
})ロケールファイルのテンプレート(カスタムロケールファイル作成時)
import dayjs from 'dayjs'
const locale = { /* ロケールオブジェクト */ }
dayjs.locale(locale, null, true)
export default localei18n
ロケールの読み込みと切り替え。
Node.js でロケールを読み込む(CommonJS)
require('dayjs/locale/de')
dayjs.locale('de')Node.js でロケールを読み込む(ES Modules)
import 'dayjs/locale/de'
dayjs.locale('de')グローバルロケールの切り替え
require('dayjs/locale/de')
dayjs.locale('de') // ドイツ語に切り替え
dayjs.locale('en') // 英語(デフォルト)に戻すグローバルロケールの変更は既存インスタンスに影響しない。新規インスタンスのみに適用される。
インスタンス単位でのロケール適用
require('dayjs/locale/de')
dayjs().locale('de').format() // このインスタンスのみドイツ語ロケールオブジェクトを変数に保存
var locale_de = require('dayjs/locale/de')
// import locale_de from 'dayjs/locale/de' // ES 2015現在のグローバルロケールを取得
dayjs.locale() // 'en'ブラウザ — CDN でロケールを読み込む(jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/locale/zh-cn.js"></script>
<script>dayjs.locale('zh-cn')</script>ブラウザ — スクリプトタグでロケールを読み込む
<script src="path/to/dayjs/locale/de"></script>
<script>
dayjs.locale('de') // グローバルに適用
dayjs().locale('de').format() // インスタンスのみに適用
</script>Install
Day.js のインストールと初期セットアップ。
npm でのインストール
npm install dayjsyarn でのインストール
yarn add dayjspnpm でのインストール
pnpm add dayjsCommonJS での読み込み
node -e "const dayjs = require('dayjs'); console.log(dayjs().format())"前提: Node.js 環境。npm install dayjs 済み。
ES Modules での読み込み(TypeScript / ESM)
# tsconfig.json に esModuleInterop: true が必要
import dayjs from 'dayjs'
dayjs().format()TypeScript 向け tsconfig.json の設定
# tsconfig.json に以下を追加
# {
# "compilerOptions": {
# "esModuleInterop": true,
# "allowSyntheticDefaultImports": true
# }
# }TypeScript では @types/dayjs は不要。Day.js 本体に型定義が同梱されている。
TypeScript でのネームスペースインポート(esModuleInterop 不要)
import * as dayjs from 'dayjs'
dayjs().format()ブラウザ — CDN(jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script>dayjs().format()</script>ブラウザ — ローカルファイル
<script src="path/to/dayjs/dayjs.min.js"></script>
<script>
dayjs().format()
</script>Plugin
プラグインの読み込みと有効化。
プラグインの読み込み(CommonJS)
var AdvancedFormat = require('dayjs/plugin/advancedFormat')
dayjs.extend(AdvancedFormat)プラグインの読み込み(ES Modules)
import AdvancedFormat from 'dayjs/plugin/advancedFormat'
dayjs.extend(AdvancedFormat)Timezone プラグインのセットアップ(UTC プラグインと合わせて使用)
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)Timezone プラグインは UTC プラグインに依存する。両方を必ずロードする。
TypeScript でのプラグイン読み込み
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear'
import 'dayjs/locale/zh-cn'
dayjs.extend(isLeapYear)
dayjs.locale('zh-cn')ブラウザ — CDN でプラグインを読み込む(jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/advancedFormat.js"></script>
<script>
dayjs.extend(window.dayjs_plugin_advancedFormat)
</script>scripts
| Name | Description | Path |
|---|---|---|
| Customization | カスタムロケールの作成と既存ロケールの更新。 | customization.md |
| i18n | ロケールの読み込みと切り替え。 | i18n.md |
| Install | Day.js のインストールと初期セットアップ。 | install.md |
| Plugin | プラグインの読み込みと有効化。 | plugin.md |
| Test | Day.js 本体のテスト・ビルド・コード品質チェック(コントリビューター向け)。 | test.md |
Test
Day.js 本体のテスト・ビルド・コード品質チェック(コントリビューター向け)。
注記: 以下のコマンドは Day.js リポジトリ自体の開発用コマンドです。Day.js を利用するプロジェクトでのテストには適用しません。
テストの実行
npm test複数タイムゾーン(Pacific/Auckland, Europe/London, America/Whitehorse)でカバレッジ 100% を検証する。
タイムゾーン固有テストの実行
npm run test-tzビルド
npm run buildBabel でコンパイルし、ファイルサイズ制限(2.99 KB)をチェックする。
Lint の実行
npm run lintsrc・test・build ディレクトリに ESLint を適用する。
コードフォーマット(ドキュメント)
npm run prettierドキュメント Markdown ファイルを Prettier でフォーマットする。
バンドルサイズの確認
npm run sizeminified バンドルが 2.99 KB 以下であることを検証する。