日期的Javascript日期格式

时间:2012-11-29 09:50:24

标签: javascript datetime

如何将Javascript中的日期格式化为例如'yyyy-MM-dd HH:mm:ss z'?

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 :)完美!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

Use this lib to make your life much easier:

var formattedDate = new Date().format('yyyy-MM-dd h:mm:ss');
document.getElementById("time").innerHTML= formattedDate;

DEMO

答案 2 :(得分:0)

基本上,我们有三种方法,您必须自己组合字符串:

  

getDate():返回日期

     

getMonth():返回月份

     

getFullYear():返回年份

示例:

  

      var d = new Date();

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