當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js Date.format()用法及代碼示例

date-and-time.Date.format()是用於操作 JS 日期和時間模塊的極簡函數集合,用於根據某種模式格式化日期。

所需模塊:通過 npm 安裝模塊或在本地使用它。

  • 通過使用 npm。
npm install date-and-time --save
  • 通過使用 CDN 鏈接。
<script src="/path/to/date-and-time.min.js"></script>

用法:

format(dateObj, formatString[, utc])

參數:此方法采用以下參數作為參數:

  • dateObj:它是日期的對象。
  • formatString:這是將顯示日期的新字符串格式。

返回值:此方法返回格式化的日期和時間。



範例1:

index.js


// Node.js program to demonstrate the  
// Date.format() method
  
// Importing module
const date = require('date-and-time')
  
// Creating object of current date and time 
// by using Date() 
const now  =  new Date();
  
// Formating the date and time
// by using date.format() method
const value = date.format(now,'YYYY/MM/DD HH:mm:ss');
  
// Display the result
console.log("current date and time:" + value)

使用以下命令運行index.js文件:

node index.js

輸出:

current date and time:2021/03/07 12:13:46

範例2:

index.js


// Node.js program to demonstrate the  
// Date.format() method
  
// Importing module
const date = require('date-and-time')
  
// Formatting the date and time
// by using date.format() method
const value = date.format((new Date('December 17, 1995 03:24:00')),
  'YYYY/MM/DD HH:mm:ss');
  
// Display the result
console.log("date and time:" + value)

使用以下命令運行index.js文件:

node index.js

輸出:

date and time:1995/12/17 03:24:00

參考:https://github.com/knowledgecode/date-and-time




相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js Date.format() API。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。