2018年8月13日 星期一

[ JS 常見問題 ] Javascript Date output formatting

Source From Here 
Question 
I need to capture the Now() date and time in the YYYY/mm/dd hh:m:sec format. It needs to be in GMT time. How do I achieve that with Javascript? 

How-To 
You can build it manually: 
- test.js 
  1. function getUTCStr(){  
  2.     var t = new Date();  
  3.     var dateStr = t.getUTCFullYear() + '/' + ("0" + (t.getUTCMonth() + 1)).slice(-2) + '/' + ("0" + (t.getUTCDate() + 1)).slice(-2) + ' ' +  
  4.                   ("0" + (t.getUTCHours() + 1)).slice(-2) + ':' +  
  5.                   ("0" + (t.getUTCMinutes() + 1)).slice(-2) + ':' +  
  6.                   ("0" + (t.getUTCSeconds() + 1)).slice(-2);  
  7.   
  8.     return dateStr  
  9. }  
  10.   
  11. function getTimeStr(){  
  12.     var t = new Date();  
  13.     var dateStr = t.getFullYear() + '/' + ("0" + (t.getMonth() + 1)).slice(-2) + '/' + ("0" + (t.getDate() + 1)).slice(-2) + ' ' +  
  14.                   ("0" + (t.getHours() + 1)).slice(-2) + ':' +  
  15.                   ("0" + (t.getMinutes() + 1)).slice(-2) + ':' +  
  16.                   ("0" + (t.getSeconds() + 1)).slice(-2);  
  17.   
  18.     return dateStr  
  19. }  
  20.   
  21. exports.getUTCStr = getUTCStr  
  22. exports.getTimeStr = getTimeStr  
Then you can use those two functions this way: 
> t = require('./test')
{ getUTCStr: [Function: getUTCStr],
getTimeStr: [Function: getTimeStr] }


> t.getUTCStr()
'2018/08/14 10:39:41'
> t.getTimeStr()
'2018/08/14 18:39:46' // My timezone is +8

Supplement 
MDN - String.prototype.slice() 
MDN - Date object

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...