js日期加减-JavaScript日期处理不再难!Day.js带你飞!

生活百科11个月前发布 aixure
51 0 0

dayjs().format('a') // am

dayjs().format('A') // AM

// @ The offset from UTC, ±HHmm
dayjs().format('ZZ') // +0100

// @ The millisecond, 3-digits
dayjs().format('SSS') // 912

dayjs().format('h:mm A  ') // 8:28 AM  

dayjs().format('h:mm:ss A') // 8:30:51 AM 

dayjs().format('MM/DD/YYYY') // 08/19/2022

dayjs().format('M/D/YYYY') // 8/19/2022

dayjs().format('ddd, hA')
// Output:  "Fri, 8AM"

dayjs().format('MMM D, YYYY'
// Aug 19, 2022

我们还可以看到一些高级的日期格式:

dayjs().format('ddd, MMM D, YYYY h:mm A ');
// @ Output: Fri, Aug 19, 2022 8:23 AM        

dayjs().format('MMM D, YYYY h:mm A');
// Aug 19, 2022 8:24 AM

dayjs().format('dddd, MMMM D YYYY, h:mm:ss A')
// Output:  "Friday, August 19 2022, 8:15:51 AM"

dayjs().format('dddd, MMMM Do YYYY, h:mm:ss A')
// output => "Friday, August 19o 2022, 8:15:51 AM"

RelativeTime 插件

在继续其他示例之前,我们来讨论一下 RelativeTime 插件。使用 RelativeTime 插件,可以将日期和时间数字转换为相对语句,例如“5小时前”。

使用CD安装浏览器:我们必须使用Relativetime CDN,然后使用Day.js设置它,以使RelativeTime插件正常工作。

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/dayjs.min.js"
    integrity="sha512-Ot7ArUEhJDU0cwoBNNnWe487kjL5wAOsIYig8llY/l0P2TUFwgsAHVmrZMHsT8NGo+HwkjTJsNErS6QqIkBxDw=="
    crossorigin="anonymous" referrerpolicy="no-referrer">

其次 从cdnjs.com获取的CDN。

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/plugin/relativeTime.min.js">

相对时间插件正在为 Day.js 进行设置:


    dayjs.extend(window.dayjs_plugin_relativeTime)    

Node.js和ES6导入的 RelativeTime 插件

当使用 npm i dayjs 时,RelativeTime 插件位于 Day.js 包内。只需要Day内的RelativeTime 路径即可使用它。

const dayjs = require('dayjs')
var relativeTime = require('dayjs/plugin/relativeTime')
dayjs.extend(relativeTime)

ES6 import

import Dayjs from "dayjs";
import relativeTIme from "dayjs/plugin/relativeTime";
Dayjs.extend(relativeTIme);

从 X 获取时间

提供表示相对于X的时间字符串。相对时间插件将使我们能够实现这一点。

始终确保使用 dayjs.extend 配置相关插件。您可以阅读更多关于 Day.js 插件的信息。

dayjs.extend(window.dayjs_plugin_relativeTime);
var a = dayjs("2022-01-01");
console.log(dayjs("2020-01-01").from(a))
// Output: 2 years ago

如果传递 true,可以获得没有后缀的值。

dayjs.extend(window.dayjs_plugin_relativeTime);
var a = dayjs("2022-01-01");
console.log(dayjs("2020-01-01").from(a, true))
// Output: 2 years

从现在开始计算时间

这将把相对于现在的时间字符串转换出来。现在需要一个RelativeTime插件。


    dayjs.extend(window.dayjs_plugin_relativeTime);
    console.log(dayjs('2000-01-01').fromNow()) 


来自未来:


    dayjs.extend(window.dayjs_plugin_relativeTime);
    console.log(dayjs('2050-01-01').fromNow()) 


// Output: in 27 years

没有后缀:您]可以使用true布尔值提供返回日期字符串。

dayjs.extend(window.dayjs_plugin_relativeTime);
dayjs('2000-01-01').fromNow(true)  // Output: 23 years

获取当前时间

这将返回一个表示相对时间到现在的字符串。请记住,这取决于相对时间插件。

dayjs.extend(window.dayjs_plugin_relativeTime);
dayjs('1980-01-01').toNow() // Output: in 43 years

缺少后缀

dayjs('1980-01-01').toNow(true) // Output: 43 years

如何生成日期的Unix时间戳

这将给出 Day.js 对象的 Unix 时间戳,即自 Unix 纪元以来的秒数。Unix 时间戳对象是 Day.js 中的内置对象,因此使用它不需要调用插件。

没有毫秒:

dayjs('2019-01-25').unix() // Output: 1548370800

以毫秒为单位:

dayjs('2019-01-25').valueOf() // Output: 1548370800000

根据 Day.js 文档,始终建议使用 Unix 时间戳。

计算一个月的天数

获取当前月份的天数,无需插件:

dayjs('2020-02-04').daysInMonth() // Output: 29

将日期作为对象返回

为了以对象格式返回日期,应该使用带有CDN的toObject插件,或在node.js或ES6导入中要求它。

CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/plugin/toObject.min.js"
    integrity="sha512-qWOc7v2jfO5Zg34fVOIfnpvDopsqDBilo8Onabl/MHIr5idHpg73tVRUGDMVOQs2dUEsmayiagk75Ihjn6yanA=="
    crossorigin="anonymous" referrerpolicy="no-referrer">

Node.js

var dayjs = require('dayjs')
var toObject = require('dayjs/plugin/toObject')
dayjs.extend(toObject)

使用 toObject() 扩展 CDN:


    dayjs.extend(window.dayjs_plugin_toObject);
    dayjs('2020-01-25').toObject()

输出:

{date: 25, hours: 0, milliseconds: 0, minutes: 0, months: 0, seconds: 0, years: 2020}

将日期作为数组返回

为了以数组格式返回日期,应该使用带有CDN的 ToArray 插件js日期加减,或在node.js或ES6导入中要求它。

CDN:

Node.js

var toArray = require('dayjs/plugin/toArray')
dayjs.extend(toArray)

dayjs.extend(window.dayjs_plugin_toArray);
dayjs('2022-08-04').toArray() // Output: [2022, 7, 4, 0, 0, 0, 0]

以 JSON 格式获取时间和日期

将其序列化为 ISO 8601 字符串格式,无需插件:

dayjs('2019-06-25').toJSON() // Output: 2019-06-24T23:00:00.000Z
dayjs('1996-01-11').toJSON() // Output: 1996-01-10T23:00:00.000Z
dayjs('2025-05-10').toJSON() // Output: 2025-05-09T23:00:00.000Z

提供日期和时间作为字符串

返回一个包含日期表示的字符串,不需要插件:

dayjs('2025-03-20').toString() // Output: Wed, 19 Mar 2025 23:00:00 GMT
dayjs('2010-08-08').toString() // Output: Sat, 07 Aug 2010 23:00:00 GMT
dayjs('01-2005-25').toString() // @ Error output: Invalid Date

解析日期

Day.js 对象是不可变的,这意味着所有修改它的 API 操作都会产生一个新的对象实例。

字符串转日期:检查以下代码以解析字符串并以日期格式返回它:

dayjs('2020-08-04T15:00:00.000Z')

一个已存在的本地 JavaScript Date 对象可以用来创建一个 Day.js 对象:

let d = new Date(2021, 02, 11);
let day = dayjs(); // The date returned by the first formatted date is copied in this line

现在使用Parse:请参见下面的代码,以使用Parse返回当前日期

new Date(2021, 02, 11);
// Alternative
dayjs(new Date());

验证

要检查日期和时间是否有效,请使用 Day.js 中的 .isValid() 方法。该方法会产生一个布尔结果:

dayjs('1996-05-01').isValid(); // Output: true
dayjs('dummy text').isValid(); // Output: false
dayjs('2005-06-09').isValid(); // Output: true

时区

Day.js为观察相同标准时间的地区提供时区兼容性。使用Day.js时区需要一个插件。要在Day.js中使用时区,我们需要同时安装时区和UTC插件:

const dayjs = require('dayjs')
const utc = require('dayjs/plugin/utc')
const timezone = require('dayjs/plugin/timezone') // dependent on utc plugin
dayjs.extend(utc)
dayjs.extend(timezone)

UTC插件的 CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/plugin/utc.min.js"
    integrity="sha512-z84O912dDT9nKqvpBnl1tri5IN0j/OEgMzLN1GlkpKLMscs5ZHVu+G2CYtA6dkS0YnOGi3cODt3BOPnYc8Agjg=="
    crossorigin="anonymous" referrerpolicy="no-referrer">

时区插件的 CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/plugin/timezone.min.js"
    integrity="sha512-fG1tT/Wn/ZOyH6/Djm8HQBuqvztPQdK/vBgNFLx6DQVt3yYYDPN3bXnGZT4z4kAnURzGQwAnM3CspmhLJAD/5Q=="
    crossorigin="anonymous" referrerpolicy="no-referrer">

Day.js 扩展时区和 UTC 插件:


    dayjs.extend(window.dayjs_plugin_utc)
    dayjs.extend(window.dayjs_plugin_timezone);

事例:

dayjs.tz("2020-06-01 12:00""America/Toronto")

在控制台上输出:

let time = {
    $D: 18,
    $H: 11,
    $L"en",
    $M: 10,
    $W: 1,
    $d"Mon Nov 18 2013 11:55:00 GMT+0100 (West Africa Standard Time) {}",
    $m: 55,
    $ms: 0,
    $offset: -300,
    $s: 0,
    $x: {
        $localOffset: -60,
        $timezone"America/Toronto"
    }
}

还可以使用 Day.js 中包含的 .toString() 方法,将时区作为普通字符串返回。

dayjs.tz("2013-11-18 11:55""America/Toronto").toString()
// Output: Mon, 18 Nov 2013 16:55:00 GMT

区解析

如果你想解析时区格式的日期,请使用名为CurrentParseFormate的插件来协助你解析时区:

Node.js

var customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)

dayjs('05/02/69 1:02:03 PM -05:00''MM/DD/YY H:mm:ss A Z')
// Returns an instance containing '1969-05-02T18:02:03.000Z'

CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/plugin/customParseFormat.min.js" integrity="sha512-FM59hRKwY7JfAluyciYEi3QahhG/wPBo6Yjv6SaPsh061nFDVSukJlpN+4Ow5zgNyuDKkP3deru35PHOEncwsw==" crossorigin="anonymous" referrerpolicy="no-referrer">

dayjs.extend(window.dayjs_plugin_customParseFormat);
dayjs.tz("12-25-1995""MM-DD-YYYY""America/Toronto").toString()
//Mon, 25 Dec 1995 05:00:00 GMT 

转换为时区

更新偏移量,切换时区,然后返回到 day.js 对象实例。当第二个参数传递一个 true 值时js日期加减,只有时区(和偏移量)被更改,而本地时间保持不变。


    dayjs.extend(window.dayjs_plugin_utc)
    dayjs.extend(window.dayjs_plugin_timezone);

估计用户时区

dayjs.extend(window.dayjs_plugin_utc)
dayjs.extend(window.dayjs_plugin_timezone);
dayjs.tz.guess()  //Asia/Calcutta

默认时区设置

将你喜欢的时区设置为默认时区,而不是本地时区。在特定的 dayjs 对象中,仍然可以自定义不同的时区

Node.js

var utc = require('dayjs/plugin/utc')
var timezone = require('dayjs/plugin/timezone') // dependent on utc plugin
dayjs.extend(utc)
dayjs.extend(timezone)

CDN

dayjs.extend(window.dayjs_plugin_utc)
dayjs.extend(window.dayjs_plugin_timezone);

dayjs.tz.setDefault("America/New_York") // Setting the default time

dayjs.tz("2019-08-05 11:00"

总结

我们首先了解了Day.js及其使用它格式化时间和日期的好处。Day.js简单地替代了Moment.js。虽然Moment.js不是必需的,但Day.js提供了所有日期格式化、解析、插件和本地化要求。因此,可以使用 dayjs.org 在官方Day.js网站上选择并查找更多信息。

原文:

最近,我们上线了一个产品AliengGpt,大家可以来体验找Bug:

体验地址:

最后:

限时特惠:本站每日持续更新海量各大内部网赚创业教程,会员可以下载全站资源点击查看详情
站长微信:

© 版权声明

相关文章

暂无评论

暂无评论...