2014-06-22 90 views
1

我使用var dateString= new Date(parseInt(dateStringUnix));,我獲得字符串爲Sun Jun 10 2012 16:40:16 GMT+0200 (ora legale Europa occidentale)格式日期javascript

現在的問題是:如何刪除字符串部分GMT+0200 (ora legale Europa occidentale)

回答

1

像這樣:

dateString = dateString.toString().replace(/ GMT.*/,""); 

以上GMT之前剛剛替換空間,和一切,包括GMT與empyt StringGMT後。

我已使用.toString()Object轉換爲String,以便可以使用.replace()

+0

你實際上需要'dateString.toString()。replace',因爲即使OP表示字符串,它仍然是一個Date。 – Scimonster

+0

@Scimonster完成..謝謝! –

0

尋找一個簡單但強大的庫,如moment.js。可能不需要,如果它是你的項目中的一個小功能,但它最終是瑞士軍刀的日期和相關的東西

0

這是我目前的最愛,因爲它既靈活又模塊化。這是(至少)三個簡單的函數的集合:

/** 
* Returns an array with date/time information 
* Starts with year at index 0 up to index 6 for milliseconds 
* 
* @param {Date} date date object. If falsy, will take current time. 
* @returns {[]} 
*/ 
getDateArray = function(date) { 
    date = date || new Date(); 
    return [ 
     date.getFullYear(), 
     exports.pad(date.getMonth()+1, 2), 
     exports.pad(date.getDate(), 2), 
     exports.pad(date.getHours(), 2), 
     exports.pad(date.getMinutes(), 2), 
     exports.pad(date.getSeconds(), 2), 
     exports.pad(date.getMilliseconds(), 2) 
    ]; 
}; 

這裏的墊功能:

/** 
* Pad a number with n digits 
* 
* @param {number} number number to pad 
* @param {number} digits number of total digits 
* @returns {string} 
*/ 
exports.pad = function pad(number, digits) { 
    return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number; 
}; 

最後,我可以用手工打造我的日期字符串,或使用一個簡單的功能做這個工作對我來說:

/** 
* Returns nicely formatted date-time 
* @example 2015-02-10 16:01:12 
* 
* @param {object} date 
* @returns {string} 
*/ 
exports.niceDate = function(date) { 
    var d = exports.getDateArray(date); 
    return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5]; 
}; 

/** 
* Returns a formatted date-time, optimized for machines 
* @example 2015-02-10_16-00-08 
* 
* @param {object} date 
* @returns {string} 
*/ 
exports.roboDate = function(date) { 
    var d = exports.getDateArray(date); 
    return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5]; 
};