2011-05-06 113 views
50

這是我需要做的。JavaScript日期到字符串

取得日期,轉換爲字符串並傳遞給第三方實用程序。 當我通過它時,庫中的響應將以字符串格式存儲日期。所以,我需要將日期轉換爲字符串如20110506105524(YYYYMMDDHHMMSS)

function printDate() { 
    var temp = new Date(); 
    var dateStr = temp.getFullYear().toString() + 
        temp.getMonth().toString() + 
        temp.getDate().toString() + 
        temp.getHours().toString() + 
        temp.getMinutes().toString() + 
        temp.getSeconds().toString(); 

    debug (dateStr); 
} 

的問題上面是對於1-9個月,它打印一個數字。我怎樣才能改變它打印月,日正好2位數...

+1

有你看着這個前一個:http://stackoverflow.com/questions/610406/javascript-printf-string-format – Liv 2011-05-06 16:07:24

+1

作爲參考,這裏是一個明確的來源: [Javascript日期對象](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date) – 2012-12-19 16:41:25

回答

57

您需要墊「0」,如果它是一個單一的數字&注getMonth收益0..11不1..12

function printDate() { 
    var temp = new Date(); 
    var dateStr = padStr(temp.getFullYear()) + 
        padStr(1 + temp.getMonth()) + 
        padStr(temp.getDate()) + 
        padStr(temp.getHours()) + 
        padStr(temp.getMinutes()) + 
        padStr(temp.getSeconds()); 
    debug (dateStr); 
} 

function padStr(i) { 
    return (i < 10) ? "0" + i : "" + i; 
} 
38

依託JQuery Datepicker,但它可以很容易做到:

var mydate = new Date(); 
$.datepicker.formatDate('yy-mm-dd', mydate); 
+2

如何使用datepicker獲取時間信息? – Siddharth 2012-04-28 16:48:58

+0

[Timepicker Addon](http://trentrichardson.com/examples/timepicker/)似乎能做到這一點。否則,我認爲[jquery-timepicker](http://jonthornton.github.com/jquery-timepicker/)看起來很好 – 2012-11-30 09:43:42

4

使用該填充工具https://github.com/UziTech/js-date-format

var d = new Date("1/1/2014 10:00 am"); 
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT"); 
//output: Wednesday the 1st of January 2014 10:00 AM 
+0

這是很好的方法,我會試試這個,謝謝。 – Deka 2016-02-02 03:23:38

1

使用正則表達式和toJSON()有點簡單。

var now = new Date(); 
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/ 
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/ 
var dateData = dateRegex.exec(now.toJSON()); 
var timeData = timeRegex.exec(now.toJSON()); 
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3] 

在撰寫本文時給出"20151111180924"

使用toJSON()的好處是所有東西都已經填充。

1

也許更容易的日期轉換爲實際的整數20110506105524,然後再轉換到這個字符串:

function printDate() { 
    var temp = new Date(); 
    var dateInt = 
     ((((temp.getFullYear() * 100 + 
      temp.getMonth() + 1) * 100 + 
      temp.getDate()) * 100 + 
      temp.getHours()) * 100 + 
     temp.getMinutes()) * 100 + 
     temp.getSeconds(); 

    debug ('' + dateInt); // convert to String 
} 

temp.getFullYear() < 1000結果將是一個(或多個)數字短。

注意:由於Number.MAX_SAFE_INTEGER是9007199254740991,它只能使用16位數字,因此無法以毫秒級精度(即17位數字)工作。

0

我喜歡Daniel Cerecedo的回答,使用toJSON()和正則表達式。一個更簡單的形式是:

var now = new Date(); 
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/; 
var token_array = regex.exec(now.toJSON()); 
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ] 
var myFormat = token_array.slice(1).join(''); 
// "20171031022445"