Quasar 提供了一组实用的函数,可以在大多数用例中轻松操作 JS 日期,而无需集成 Momentjs 等专用库的高昂额外成本。
¥Quasar provides a set of useful functions to manipulate JS Date easily in most use cases, without the high additional cost of integrating dedicated libraries like Momentjs.
大多数 Quasar 日期函数将 Unix 时间戳或表示日期的字符串作为参数,该字符串需要由原生 JS 日期构造函数 解析。一些示例:1497159857411
, Sun Jun 11 2017 08:44:42 GMT+0300
, 2017-06-16
.
¥Most Quasar date functions take as parameter either a Unix timestamp or a String representing a date which needs to be parsable by the native JS Date constructor. Some examples: 1497159857411
, Sun Jun 11 2017 08:44:42 GMT+0300
, 2017-06-16
.
返回值均为 JS 日期。
¥Returned values are all JS Dates.
熟悉 JS 原生 Date 类,它非常强大,记住你不需要像 Momentjs 这样的解决方案,它会给你的打包文件增加数百 KB 的压缩体积。
¥Get familiar with JS native Date class, which is very powerful, and remember that you don’t need solutions like Momentjs which add hundreds of minified KB to your bundle.
提示
Quasar date utils 包含 tree shake(UMD 版本除外)。
¥Quasar date utils includes tree shaking, except for the UMD version.
你会注意到所有示例都从 Quasar 导入了 date
对象。但是,如果你只需要其中的一个方法,那么你可以使用 ES6 解构来帮助 Tree Shaking 仅嵌入该方法,而不是 date
的全部。
¥You will notice all examples import date
Object from Quasar. However, if you need only one method from it, then you can use ES6 destructuring to help Tree Shaking embed only that method and not all of date
.
addToDate()
示例:
¥Example with addToDate()
:
// we import all of `date`
import { date } from 'quasar'
// destructuring to keep only what is needed
const { addToDate } = date
const newDate = addToDate(new Date(), { days: 7, months: 1 })
显示格式(Format for display)
¥Format for display
它接受一串 token,并将其替换为相应的日期值:
¥It takes a string of tokens and replaces them with their corresponding date values:
import { date } from 'quasar'
const timeStamp = Date.now()
const formattedString = date.formatDate(timeStamp, 'YYYY-MM-DDTHH:mm:ss.SSSZ')
对于国际化,你可以使用第三个参数:
¥For i18n, you can use a third parameter:
const formattedString = date.formatDate(timeStamp, 'MMMM - dddd', {
days: ['Duminica', 'Luni', /* and all the rest of days - remember starting with Sunday */],
daysShort: ['Dum', 'Lun', /* and all the rest of days - remember starting with Sunday */],
months: ['Ianuarie', 'Februarie', /* and all the rest of months */],
monthsShort: ['Ian', 'Feb', /* and all the rest of months */]
})
可用的格式标记:
¥Available format tokens:
单元 | 可用格式 |
---|---|
年份 | |
月份 | |
季度 | |
日期 | |
年中日期 | |
日期周 | |
星期几 (ISO) | |
年份中的周 | |
小时 | |
分钟 | |
第二个 | |
小数秒 | |
时区偏移 | |
AM/PM | |
Unix 时间戳 |
如果你想在掩码中插入字符串(包括 [
和 ]
字符),请确保使用 [
和 ]
将它们括起来进行转义,否则这些字符可能会被解释为格式标记。
¥If you want to insert strings (including [
and ]
characters) into your mask, make sure you escape them by surrounding them with [
and ]
, otherwise the characters might be interpreted as format tokens.
操作日期(Manipulate dates)
¥Manipulate dates
创建(Create)
¥Create
尝试使用原生 JS Date 类创建日期,如下所示:
¥Try to create dates with native JS Date class like so:
const date = new Date();
以下方法只是一个封装器,可在你只需要当前时间但需要不同年份、月份或秒等的情况下为你提供帮助。
¥The following method is just a wrapper to help you in cases where you just need current time but with a different year, or month, or second etc.
import { date } from 'quasar'
const newDate = date.buildDate({ year: 2010, date: 5, hours: 15, milliseconds: 123 })
你可以传递第二个参数(布尔值)来设置 UTC 时间 (true) 而不是本地时间。
¥You can pass a second argument (a boolean) for setting UTC time (true) instead of local time.
提供的对象字面量可以包含以下键(所有键均为可选):
¥The object literal provided can contain the following keys (all are optional):
密钥 | 描述 |
---|---|
millisecond(s) | 日期/时间的毫秒部分 |
second(s) | 日期/时间的秒部分 |
minute(s) | 日期/时间的分钟部分 |
hour(s) | 日期/时间的小时部分 |
day(s) / date | 日期/时间的日期部分 |
month(s) | 日期/时间的月份部分 |
year(s) | 日期/时间的年份部分 |
验证(Validate)
¥Validate
要检查日期字符串是否有效,请使用:
¥To check if a date string is valid use:
import { date } from 'quasar'
const dateString = 'Wed, 09 Aug 1995 00:00:00 GMT'
if (date.isValid(dateString)) {
// Do something with date string
}
警告
isValid
仅验证日期格式,而不验证日期的逻辑有效性。
¥isValid
only validates the date format, not the logic validity of the date.
底层实现基于原生 Date.parse(...)
API,其缺陷将通过我们的 API 传递。
¥The underlying implementation is based on native Date.parse(...)
API and its shortcomings will pass through our API.
它不会检查日期是否按月份有效(例如 2 月 31 日),也不会检查日期是否按年份有效(例如非闰年的 2 月 29 日),并且在 Firefox 和基于 Chromium 的浏览器(Chrome、Edge 等)中,对于这些情况,它将返回不同的值。
¥It will not check if the date is valid for the month (e.g. 31st of February), or if the date is valid for the year (e.g. 29th of February in a non-leap year), and will return a different value in those cases for Firefox with respect to Chromium-based browsers (Chrome, Edge, etc).
添加/删除(Add/Subtract)
¥Add/Subtract
要为日期添加/减少一些持续时间,请使用:
¥To add/subtract some duration to/from a date use:
import { date } from 'quasar'
let newDate = new Date(2017, 2, 7)
newDate = date.addToDate(newDate, { days: 7, months: 1 })
// `newDate` is now 2017-3-14 00:00:00
newDate = date.subtractFromDate(newDate, { hours: 24, milliseconds: 10000 })
// `newDate` is now 2017-3-12 23:59:50
提供的对象字面量可以包含以下键(所有键均为可选):
¥The object literal provided can contain the following keys (all are optional):
密钥 | 描述 |
---|---|
millisecond(s) | 持续时间(以毫秒为单位) |
second(s) | 持续时间(以秒为单位) |
minute(s) | 持续时间(以分钟为单位) |
hour(s) | 持续时间(以小时为单位) |
day(s) / date | 持续时间(以天为单位) |
month(s) | 持续时间(以月为单位) |
year(s) | 持续时间(以年为单位) |
设置日期/时间(Set date/time)
¥Set date/time
要设置指定的日期/时间单位:
¥To set a specified unit(s) of date/time:
import { date } from 'quasar'
const newDate = new Date(2017, 10, 2)
const adjustedDate = date.adjustDate(newDate, { year: 2010, month: 2 })
// `adjustedDate` is 2010-2-2
你可以传递第三个参数(布尔值)来设置 UTC 时间 (true
) 而不是本地时间。
¥You can pass a third argument (a Boolean) for setting UTC time (true
) instead of local time.
提供的对象字面量可以包含以下键(所有键均为可选):
¥The object literal provided can contain the following keys (all are optional):
密钥 | 描述 |
---|---|
millisecond(s) | 日期/时间的毫秒部分 |
second(s) | 日期/时间的秒部分 |
minute(s) | 日期/时间的分钟部分 |
hour(s) | 日期/时间的小时部分 |
day(s) / date | 日期/时间的日期部分 |
month(s) | 日期/时间的月份部分 |
year(s) | 日期/时间的年份部分 |
查询日期(Query dates)
¥Query dates
最小/最大(Minimum/Maximum)
¥Minimum/Maximum
要获取日期集(即数组)的最小/最大日期,请使用:
¥To get the minimum/maximum date of a date set (i.e. array) use:
import { date } from 'quasar'
let min = date.getMinDate(new Date(2017, 6, 24), new Date(2017, 5, 20), new Date(2017, 6, 26))
// `min` is 2017-5-20
let max = date.getMaxDate(new Date(2017, 6, 24), new Date(2017, 5, 20), new Date(2017, 6, 26))
// `max` is 2017-6-26
// Or use an array:
const dates = [ new Date(2017, 6, 24), new Date(2017, 5, 20), new Date(2017, 6, 26) ]
let min = date.getMinDate(...dates) // `min` is 2017-5-20
let max = date.getMaxDate(...dates) // `max` is 2017-6-26
请注意,返回值是一个时间戳。
¥Note that the returning value is a timestamp.
console.log(max) // 1497906000000
console.log(new Date(max)) // Wed Jul 26 2017 00:00:00 GMT+0300 (Eastern European Summer Time)
时间范围(Time range)
¥Time range
要检查日期是否在给定的日期/时间范围内,请使用:
¥To check if a date is in a given date/time range use:
import { date } from 'quasar'
const dateTarget = new Date()
const dateFrom = new Date()
const dateTo = new Date()
// **strictly** (i.e. exclusive range)
if (date.isBetweenDates(dateTarget, dateFrom, dateTo)) {
// Do something with dateTarget
}
// including which margin you want
if (date.isBetweenDates(dateTarget, dateFrom, dateTo, { inclusiveFrom: true, inclusiveTo: true })) {
// Do something with dateTarget
}
// if you only care about comparing dates (year/month/day, regardless of time)
// then you could tip isBetweenDates() about it so it can perform best:
if (date.isBetweenDates(dateTarget, dateFrom, dateTo, { onlyDate: true })) {
// Do something with dateTarget
}
要在给定的日期/时间范围内规范化日期,请使用:
¥To normalize a date in a given date/time range use:
import { date } from 'quasar'
const newDate = new Date()
const dateMin = new Date(2010, 2, 23)
const dateMax = new Date(2012, 4, 12)
const dateNormalized = date.getDateBetween(newDate, dateMin, dateMax)
// Returns `newDate` if it's between 2010-2-23 and 2012-4-12; `dateMin` if it's lower; `dateMax` if it's greater
平等(Equality)
¥Equality
要检查两个日期的单位是否相等,请使用:
¥To check if two dates’ unit are equal use:
import { date } from 'quasar'
const date1 = new Date(2017, 2, 5)
const date2 = new Date(2017, 3, 8)
const unit = 'year'
if (date.isSameDate(date1, date2, /* optional */ unit)) {
// true because date1 and date2's year is the same
}
Unit 参数可以省略,在这种情况下将进行完整的日期/时间比较,否则允许进行部分比较:
¥Unit parameter can be omitted, in which case a full date/time comparison will occur, otherwise it allows to perform partial comparison:
单元 | 描述 |
---|---|
second(s) | 仅测试是否为同一秒 |
minute(s) | 仅测试是否为同一分钟 |
hour(s) | 仅测试是否为同一小时 |
day(s) / date | 仅测试是否为同一天 |
month(s) | 仅测试是否为同一月份 |
year(s) | 仅测试是否为同一年份 |
区别(Difference)
¥Difference
要计算两个日期之间的差值,请使用:
¥To compute the difference between two dates use:
import { date } from 'quasar'
const date1 = new Date(2017, 4, 12)
const date2 = new Date(2017, 3, 8)
const unit = 'days'
const diff = date.getDateDiff(date1, date2, unit)
// `diff` is 34 (days)
unit 参数表示计量单位,如果未指定,则默认为 days
:
¥The unit parameter indicates the unit of measurement, if not specified then it is days
by default:
单元 | 描述 |
---|---|
second(s) | 以秒为单位的距离(不考虑毫秒) |
minute(s) | 以分钟为单位的距离(不考虑秒等) |
hour(s) | 以小时为单位的距离(不考虑分钟、秒等) |
day(s) / date | 以日历天为单位的距离 |
month(s) | 以日历月为单位的距离 |
year(s) | 距离按日历年计算 |
日历(Calendar)
¥Calendar
要获取给定日期对象的 ISO 年份中的周数,请使用:
¥To get the ISO week number in year for a given date object use:
import { date } from 'quasar'
const newDate = new Date(2017, 0, 4)
const week = date.getWeekOfYear(newDate) // `week` is 1
要获取给定日期对象在一年中的天数,请使用:
¥To get the day number in year for a given date object use:
import { date } from 'quasar'
const newDate = new Date(2017, 1, 4)
const day = date.getDayOfYear(newDate) // `day` is 35
要获取给定日期对象在一周中的天数,请使用:
¥To get the day number in week for a given date object use:
import { date } from 'quasar'
const newDate = new Date(2017, 1, 9)
const day = date.getDayOfWeek(newDate) // `day` is 4
要获取指定日期在一个月中的天数,请使用:
¥To get the number of days in the month for the specified date:
import { date } from 'quasar'
const newDate = new Date()
const days = date.daysInMonth(newDate) // e.g. 30
开始/结束时间(Start/End of time)
¥Start/End of time
要通过将原始日期对象设置为时间单位的起始值来对其进行修改,请使用:
¥To mutate the original date object by setting it to the start of a unit of time use:
import { date } from 'quasar'
let newDate = new Date('2000')
// set to beginning of year 2000 (January 1st, 2000, 00:00:00.000)
newDate = date.startOfDate(newDate, 'year')
// set to end of year 2000 (December 31st, 2000, 23:59:59.999)
newDate = date.endOfDate(newDate, 'year')
第二个参数指示要重置到的单位(单位的开头或结尾):
¥The second parameter indicates a unit to reset to (beginning of it or end of it):
单元 | 描述 |
---|---|
second(s) | 重置秒数 |
minute(s) | 重置分钟数 |
hour(s) | 重置小时数 |
day(s) / date | 重置天数 |
month(s) | 重置月份 |
year(s) | 重置年份 |
其他(Other)
¥Other
获取格式(Get Format)
¥Get Format
import { date } from 'quasar'
date.inferDateFormat(new Date()) // 'date'
date.inferDateFormat(35346363) // 'number'
date.inferDateFormat('Mon Feb 05 2018 23:05:29') // string
克隆日期(Cloning Date)
¥Cloning Date
import { date } from 'quasar'
const newDate = new Date()
const clonedDate = date.clone(newDate)
date.addToDate(newDate, { days: 1 })
console.log(newDate.getDate() === clonedDate.getDate()) // false
提取日期(Extract Date)
¥Extract Date
使用当前 Quasar 语言包设置的语言环境,你可以根据传递的格式将任何字符串解析为日期对象:
¥Using locale set by current Quasar language pack, this allows you to parse any string into a date object based on the format passed:
import { date } from 'quasar'
// Example 1
const date = date.extractDate('2019-10-29 --- 23:12', 'YYYY-MM-DD --- HH:mm')
// date is a new Date() object
// Example 2
const date = date.extractDate('21/03/1985', 'DD/MM/YYYY')
// date is a new Date() object
使用可选的自定义语言环境:
¥With optional custom locale:
import { date } from 'quasar'
const obj = date.extractDate('Month: Feb, Day: 11th, Year: 2018', '[Month: ]MMM[, Day: ]Do[, Year: ]YYYY', {
days: ['Duminica', 'Luni', /* and all the rest of days - remember starting with Sunday */],
daysShort: ['Dum', 'Lun', /* and all the rest of days - remember starting with Sunday */],
months: ['Ianuarie', 'Februarie', /* and all the rest of months */],
monthsShort: ['Ian', 'Feb', /* and all the rest of months */]
})
// obj is a new Date() object