2012-01-13 124 views
8

我有一個日期/時間字符串,如2012-01-13 04:37:20,但我想將其轉換爲dd-mm-yyyy hh:mm,我該如何做到這一點?使用Javascript格式化日期時間

我正在使用下面的代碼,但它會引發異常。

var now = "2012-01-13 04:37:20"; 
var dd = now.toLocaleDateString() + " " + now.toLocaleTimeString(); 
alert(dd); 

回答

8

您可以執行簡單的字符串操作並創建js日期對象。見下文功能,它接受日期格式// YYYY-MM-DD HH:MM:SS

DEMO這裏

function toJSDate (dateTime) { 

var dateTime = dateTime.split(" ");//dateTime[0] = date, dateTime[1] = time 

var date = dateTime[0].split("-"); 
var time = dateTime[1].split(":"); 

//(year, month, day, hours, minutes, seconds, milliseconds) 
return new Date(date[0], date[1], date[2], time[0], time[1], time[2], 0); 

} 
+5

'日[1]'應該是'日期[1] - 1'爲一個月的正確的輸出。 – Dzhuang 2015-07-19 17:05:06

-2

你的變量現在是一個String對象和toLocaleDateString方法需要Date對象。請參閱w3schools

5

使用任一簡單字符串操作(如由@SKS建議的)或使用一個庫。後者更靈活,可以讓您輕鬆更改輸入或輸出格式。例如,使用Globalize.js庫,你可以這樣寫:

var dd = Globalize.parseDate(now, "yyyy-MM-dd HH:mm:ss"); 
dd = Globalize.format(dd, "dd-MM-yyyy HH:mm"); 

然而要注意格式,如「DD-MM-YYYY HH:MM」令人困惑 - 這既不是一個標準的ISO格式,也沒有任何本地化(語言 - 依賴)格式。 Globalize.js庫允許您使用預定義的語言相關格式以及明確指定的格式。

請注意,JavaScript中的內置日期和時間解析和格式化例程是依賴於實現的。使用它們意味着不可移植的代碼。例如,不能保證new Date()將接受您作爲輸入的格式,toLocaleDateString()會以某種與語言環境相關的格式寫入日期,該格式可以是任何事情。

3

的最佳日期,時間在JavaScript處理的lib是moment.

moment().format('MMMM Do YYYY, h:mm:ss a'); 
4

如果你並不需要所有的像Moment.js庫提供,那麼你可以使用我的strftime端口的功能。它的重量輕(1.35 KB比57.9 KB縮小了Moment.js 2.15.0),並提供了strftime()的大部分功能。

/* Port of strftime(). Compatibility notes: 
* 
* %c - formatted string is slightly different 
* %D - not implemented (use "%m/%d/%y" or "%d/%m/%y") 
* %e - space is not added 
* %E - not implemented 
* %h - not implemented (use "%b") 
* %k - space is not added 
* %n - not implemented (use "\n") 
* %O - not implemented 
* %r - not implemented (use "%I:%M:%S %p") 
* %R - not implemented (use "%H:%M") 
* %t - not implemented (use "\t") 
* %T - not implemented (use "%H:%M:%S") 
* %U - not implemented 
* %W - not implemented 
* %+ - not implemented 
* %% - not implemented (use "%") 
* 
* strftime() reference: 
* http://man7.org/linux/man-pages/man3/strftime.3.html 
* 
* Day of year (%j) code based on Joe Orost's answer: 
* http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366 
* 
* Week number (%V) code based on Taco van den Broek's prototype: 
* http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html 
*/ 
function strftime(sFormat, date) { 
    if (!(date instanceof Date)) date = new Date(); 
    var nDay = date.getDay(), 
    nDate = date.getDate(), 
    nMonth = date.getMonth(), 
    nYear = date.getFullYear(), 
    nHour = date.getHours(), 
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], 
    isLeapYear = function() { 
     return (nYear%4===0 && nYear%100!==0) || nYear%400===0; 
    }, 
    getThursday = function() { 
     var target = new Date(date); 
     target.setDate(nDate - ((nDay+6)%7) + 3); 
     return target; 
    }, 
    zeroPad = function(nNum, nPad) { 
     return ('' + (Math.pow(10, nPad) + nNum)).slice(1); 
    }; 
    return sFormat.replace(/%[a-z]/gi, function(sMatch) { 
    return { 
     '%a': aDays[nDay].slice(0,3), 
     '%A': aDays[nDay], 
     '%b': aMonths[nMonth].slice(0,3), 
     '%B': aMonths[nMonth], 
     '%c': date.toUTCString(), 
     '%C': Math.floor(nYear/100), 
     '%d': zeroPad(nDate, 2), 
     '%e': nDate, 
     '%F': date.toISOString().slice(0,10), 
     '%G': getThursday().getFullYear(), 
     '%g': ('' + getThursday().getFullYear()).slice(2), 
     '%H': zeroPad(nHour, 2), 
     '%I': zeroPad((nHour+11)%12 + 1, 2), 
     '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3), 
     '%k': '' + nHour, 
     '%l': (nHour+11)%12 + 1, 
     '%m': zeroPad(nMonth + 1, 2), 
     '%M': zeroPad(date.getMinutes(), 2), 
     '%p': (nHour<12) ? 'AM' : 'PM', 
     '%P': (nHour<12) ? 'am' : 'pm', 
     '%s': Math.round(date.getTime()/1000), 
     '%S': zeroPad(date.getSeconds(), 2), 
     '%u': nDay || 7, 
     '%V': (function() { 
       var target = getThursday(), 
       n1stThu = target.valueOf(); 
       target.setMonth(0, 1); 
       var nJan1 = target.getDay(); 
       if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7); 
       return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2); 
      })(), 
     '%w': '' + nDay, 
     '%x': date.toLocaleDateString(), 
     '%X': date.toLocaleTimeString(), 
     '%y': ('' + nYear).slice(2), 
     '%Y': nYear, 
     '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'), 
     '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1') 
    }[sMatch] || sMatch; 
    }); 
} 

使用範例:

// Returns "15-09-2016 16:20" 
strftime('%d-%m-%Y %H:%M'); 

// You can optionally pass it a Date object 
// Returns "01-01-2016 21:30" 
strftime('%d-%m-%Y %H:%M', new Date('Jan 1, 2016 9:30 PM')); 

最新的代碼可以在這裏找到:https://github.com/thdoan/strftime

0

一個小功能,如下圖:

var formatTime = function(time, format){ 
time = typeof time == 'number' ? new Date(time) : time; 
format = format || 'yyyy-mm-dd hh:MM:ss'; 
var year = time.getFullYear(); 
var month = time.getMonth() + 1; 
var date = time.getDate(); 
var hours = time.getHours(); 
var minutes = time.getMinutes(); 
var seconds = time.getSeconds(); 
var add0 = function(t){return t < 10 ? '0' + t : t} 
var replaceMent = { 
    'yyyy': year, 
    'mm': add0(month), 
    'm': month, 
    'dd': add0(date), 
    'd': date, 
    'hh': add0(hours), 
    'h': hours, 
    'MM': add0(minutes), 
    'M': minutes, 
    'ss': add0(seconds), 
    's': seconds 
} 
for(var k in replaceMent){ 
    format = format.replace(k, replaceMent[k]); 
} 
return format; 

}

1

我認爲最好使用Intl.DateTimeFormat類。

用法相當簡單。你不能按照你的想法輸入模式,但它會給你想要的結果。

下面是關於如何使用它的一個例子:

public formatDate(date : Date) : string{ 
    var options = { year: 'numeric', month: 'short', day: 'numeric' }; 
    return new Intl.DateTimeFormat('de-DE', options).format(date); 
} 

如果你真的想進入DateTimeFormat字符串,這將是很容易寫一個解析使用正則表達式的字符串的函數,但我不不認爲這是必要的。

更多信息請點擊這裏:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

+0

很高興知道這是存在的,但這並不適用於所有平臺,如mozilla參考中所述 – 2017-09-06 13:55:42

0

對於DateTime是否在JavaScript中,最好使用 'Intl.DateTimeFormat' 如下工作:

var date = new Date('2012-01-13 14:37:20'); 
var options = { year: 'numeric', month: '2-digit', day: '2-digit', 
hour:'2-digit', minute: '2-digit',hour12: false}; 
console.log(new Intl.DateTimeFormat('en-US', options).format(date).replace(/\//g,'-').replace(',','')); 

結果:「01- 13-2012 14:37「

日期和時間格式可以使用選項參數自定義。

Check Online

0

容易被我date-shortcode包來完成:

const dateShortcode = require('date-shortcode') 
dateShortcode.parse('{DD-MM-YYYY hh:mm}', '2012-01-13 04:37:20') 
//=> '13-01-2012 04:37'