Moment.js moment().toDate() 方法

Moment.js moment().toDate() 方法

moment().toDate() 方法用于将 Moment 对象转换为原生 JavaScript 对象。然后可以将该 Date 对象与原生 Date 方法一起使用,或者用于其他库的支持。

语法:

moment().toDate();

参数: 该方法不接受任何参数:

返回值: 该方法以原生JavaScript的Date格式返回Moment对象。

注意: 这在普通的Node.js程序中不起作用,因为它需要全局安装或者在项目目录中安装外部的moment.js库。

Moment.js可以使用以下命令进行安装:

moment模块的安装:

npm install moment

下面的示例将演示 Moment.js moment().toDate() 方法。

示例1:

const moment = require('moment'); 
  
let momentOne = moment(); 
let momentTwo = moment().add(10, 'days'); 
let momentThree = moment().add(10, 'hours'); 
  
console.log( 
    "Native Date object of momentOne is:", 
    momentOne.toDate() 
) 
console.log( 
    "Native Date object of momentTwo is:", 
    momentTwo.toDate() 
) 
console.log( 
    "Native Date object of momentThree is:", 
    momentThree.toDate() 
)

输出:

Native Date object of momentOne is: 2022-07-10T17:24:21.114Z
Native Date object of momentTwo is: 2022-07-20T17:24:21.114Z
Native Date object of momentThree is: 2022-07-11T03:24:21.115Z

示例2:

const moment = require('moment'); 
  
let momentA = moment('25/12/2022', 'DD/MM/YYYY'); 
let momentB = moment({ 
    year: 2017, month: 5, day: 4, 
    hour: 1, minute: 15, second: 30, 
    millisecond: 100 
}); 
  
console.log( 
    "Native Date object of momentA is:", 
    momentA.toDate() 
) 
console.log( 
    "Native Date object of momentB is:", 
    momentB.toDate() 
)

输出:

Native Date object of momentA is: 2022-12-24T18:30:00.000Z
Native Date object of momentB is: 2017-06-03T19:45:30.100Z

参考: https://momentjs.com/docs/#/displaying/as-javascript-date/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程