Moment.js 自定义相对时间舍入

Moment.js 自定义相对时间舍入

Moment.js 是一个用于解析、验证、操作和格式化日期的JavaScript日期库。 Moment.js 自定义 相对时间舍入 用于按需求将时间舍入。在这里, 相对 表示时间将根据当前时间进行舍入。我们可以使用 moment.relativeTimeRounding 来控制舍入。

语法:

moment.relativeTimeRounding( function );
JavaScript

参数: 该方法接受一个参数,指定需要进行的舍入方式。下面列出了一些可用的参数:

  • Math.ceil 将相对时间计算舍入为较大的整数。
  • Math.floor 将相对时间计算舍入为较小的整数。

返回值: 该函数返回舍入到当前时间的时间。

注意: 在普通的Node.js程序中,这个方法不会生效,因为需要安装moment.js库。

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

npm install moment
JavaScript

示例1: 在这里,我们将向当前时间倒退一小时。为此,我们需要将 Math.floor 作为参数传递。

const moment = require("moment"); 
  
// Round relative time evaluation down 
moment.relativeTimeRounding(Math.floor); 
  
let a = moment(); 
a.toNow(); // Current time 
console.log("Current time is:", a); 
  
// Rounding-down time to one-hr behind 
a.subtract({ minutes: 59 }); 
console.log("Rounded-down time is:", a);
JavaScript

输出:

Current time is:  Moment<2022-11-30T19:38:20+05:30>
Rounded-down time is:  Moment<2022-11-30T18:39:20+05:30>
JavaScript

示例2: 在这里,我们将向当前时间提前一天。为此,我们需要将 Math.ceil 作为参数传递。

const moment = require("moment"); 
  
// Round relative time evaluation up 
moment.relativeTimeRounding(Math.ceil); 
  
let a = moment(); 
a.toNow(); 
console.log("Current time is: ", a); 
  
// Rounding-up time to one-day ahead 
a.add({ hours: 23, minutes: 59, seconds: 59 }); 
console.log("Rounded-up time is: ", a);
JavaScript

输出:

Current time is:  Moment<2022-11-30T19:41:59+05:30>
Rounded-up time is:  Moment<2022-12-01T19:41:58+05:30>
JavaScript

参考资料: https://momentjs.com/docs/#/customization/relative-time-rounding

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册