Moment.js moment.duration().toJSON() 方法

Moment.js moment.duration().toJSON() 方法

moment().duration().toJSON() 方法用于获取持续时间的 JSON 格式。在序列化过程中,使用 ISO8601 格式将持续时间转换为适合 JSON 输出的格式。

注意: 如果持续时间本身无效,则会返回一个无效日期。

语法:

moment().duration().toJSON();

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

返回值: 该方法以JSON格式返回持续时间。

注意: 在常规的Node.js程序中,该方法不起作用,因为它需要全局安装moment.js库或在项目目录中安装。

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

安装Moment模块:

npm install moment

示例1: 此示例将演示Moment.js的 moment().duration().toJSON() 方法

const moment = require('moment'); 
  
let readingTime = moment.duration(10, 'minutes'); 
let lastUpdated = moment.duration(-9, 'months'); 
  
let blogPost = { 
    title: "Blog One", 
    readingTime: readingTime.toJSON(), 
    lastUpdated: lastUpdated.toJSON() 
} 
  
console.log(JSON.stringify(blogPost));

输出:

{
    "title": "Blog One",
    "readingTime": "PT10M",
    "lastUpdated": "-P9M"
}

示例2:

const moment = require('moment'); 
  
let datetime =  
    moment.duration({months: 5, days: 2, hours: 4, seconds: 1}); 
let time =  
    moment.duration({hours: 5, minutes: 6, seconds: 55}); 
let date =  
    moment.duration({years: 10, months: 5, days: 10}); 
  
let exampleJSON = { 
    durationA: datetime.toJSON(), 
    durationB: time.toJSON(), 
    durationC: date.toJSON() 
} 
  
console.log(JSON.stringify(exampleJSON));

输出:

{
    "durationA": "P5M2DT4H1S",
    "durationB": "PT5H6M55S",
    "durationC": "P10Y5M10D"
}

参考资料: https://momentjs.com/docs/#/durations/as-json/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程