当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Moment.js moment().local()用法及代码示例


moment().local() 方法用于指定给定 Moment 对象的时区将显示在用户的本地时区中。可以传递一个可选参数,该参数保留当前时间值,并且仅将时区更改为本地时区。

用法:

moment().local( Boolean );

参数:该方法接受如上所述和如下所述的单个参数:

  • Boolean: 它是一个布尔值,指定是否在不更改实际时间本身的情况下更改时区。

返回值:此方法返回具有新时区的 Moment 对象。

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

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

moment模块的安装:

npm install moment

以下示例将演示 Moment.js moment().local() 方法。

示例 1:

Javascript


const moment = require('moment'); 
  
let nowMoment = moment.utc(); 
  
console.log( 
    "Current Moment is:", nowMoment.toString() 
) 
console.log( 
    "Current Hours:", nowMoment.hours() 
) 
console.log( 
    "Current Minutes:", nowMoment.minutes() 
) 
  
// Set the Time to display in the local timezone 
nowMoment.local() 
  
console.log( 
    "Current Moment is:", nowMoment.toString() 
) 
console.log( 
    "Current Hours:", nowMoment.hours() 
) 
console.log( 
    "Current Minutes:", nowMoment.minutes() 
)

输出:

Current Moment is: Sun Jul 24 2022 17:47:57 GMT+0000
Current Hours: 17
Current Minutes: 47
Current Moment is: Sun Jul 24 2022 23:17:57 GMT+0530
Current Hours: 23
Current Minutes: 17

示例 2:

Javascript


const moment = require('moment'); 
  
let nowMoment2 = moment( 
    "2001-07-05T05:01:27"
).locale("br"); 
  
console.log( 
    "Current Moment is:", nowMoment2.toString() 
) 
console.log( 
    "Current Hours:", nowMoment2.hours() 
) 
console.log( 
    "Current Minutes:", nowMoment2.minutes() 
) 
  
// Change only the timezone and not the actual 
// time of the Moment  
nowMoment2.local(true) 
  
console.log( 
    "Current Moment is:", nowMoment2.toString() 
) 
console.log( 
    "Current Hours:", nowMoment2.hours() 
) 
console.log( 
    "Current Minutes:", nowMoment2.minutes() 
)

输出:

Current Moment is: Thu Jul 05 2001 05:01:27 GMT+0530
Current Hours: 5
Current Minutes: 1
Current Moment is: Thu Jul 05 2001 05:01:27 GMT+0530
Current Hours: 5
Current Minutes: 1

参考: https://momentjs.com/docs/#/manipulating/local/



相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Moment.js moment().local() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。