2012-11-29 83 views
0

如何在Javascript中將日期格式化爲某個日期'yyyy-MM-dd HH:mm:ss z'?日期的Javascript日期格式

date.toString('yyyy-MM-dd HH:mm:ss z');從來沒有制定出對我來說:/

任何想法?

======

我解決我自己的,我重寫這樣的:

var parseDate = function(date) { 
    var m = /^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d) UTC$/.exec(date); 
    var tzOffset = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTimezoneOffset(); 

    return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5] - tzOffset, +m[6]); 
} 

var formatDateTime = function(data) { 
    var utcDate = parseDate(data); 

    var theMonth = utcDate.getMonth() + 1; 
    var myMonth = ((theMonth < 10) ? "0" : "") + theMonth.toString(); 

    var theDate = utcDate.getDate(); 
    var myDate = ((theDate < 10) ? "0" : "") + theDate.toString(); 

    var theHour = utcDate.getHours(); 
    var myHour = ((theHour < 10) ? "0" : "") + theHour.toString(); 

    var theMinute = utcDate.getMinutes(); 
    var myMinute = ((theMinute < 10) ? "0" : "") + theMinute.toString(); 

    var theSecond = utcDate.getSeconds(); 
    mySecond = ((theSecond < 10) ? "0" : "") + theSecond.toString(); 

    var theTimezone = new Date().toString(); 
    var myTimezone = theTimezone.indexOf('(') > -1 ? 
      theTimezone.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') : 
      theTimezone.match(/[A-Z]{3,4}/)[0]; 

    if (myTimezone == "GMT" && /(GMT\W*\d{4})/.test(theTimezone)) { 
     myTimezone = RegExp.$1; 
    } 

    if (myTimezone == "UTC" && /(UTC\W*\d{4})/.test(theTimezone)) { 
     myTimezone = RegExp.$1; 
    } 

    var dateString = utcDate.getFullYear() + "-" + 
        myMonth + "-" + 
        myDate + " " + 
        myHour + ":" + 
        myMinute + ":" + 
        mySecond + " " + 
        myTimezone; 

    return dateString; 
} 

,我也得到:2012年11月15日22時08分08秒MPST :)完美!

+0

可能重複的[如何顯示的日期和在JavaScript 2007年2月25日的格式,如果我有日期對象](HTTP:/ /stackoverflow.com/questions/1536516/how-to-display-a-date-as-2-25-2007-format-in-javascript-if-i-have-date-object) –

+0

這不是一個確切的副本,但這是同樣的問題,你應該從那裏弄清楚。 –

+0

我讀過一個,一些使用外部腳本。我想要一些純粹的功能。 – lannyboy

回答

1
function formatDate(dateObject) //pass date object 
{ 
    return (dateObject.getFullYear() + "-" + dateObject.getMonth() + 1) + "-" + dateObject.getDate() ; 
} 
0

基本上,我們有三種方法,你必須琴絃爲自己結合:

GETDATE():返回日期

得到月():返回月份

和getFullYear():返回年份

例子:

變種d =新的日期();

var curr_date = d.getDate(); 

var curr_month = d.getMonth() + 1; //Months are zero based 
var curr_year = d.getFullYear(); 
document.write(curr_date + "-" + curr_month + "-" + curr_year); </script> 

更多細節看10 steps to format date and time並且還check this