0

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

4

3 回答 3

1
function formatDate(dateObject) //pass date object
{
  return (dateObject.getFullYear() + "-" + (dateObject.getMonth() + 1)) + "-" + dateObject.getDate()   ;
}
于 2012-11-29T10:00:28.460 回答
0

使用这个库让你的生活更轻松:

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

演示

于 2012-11-29T09:59:54.610 回答
0

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

getDate():返回日期

getMonth():返回月份

getFullYear():返回年份

例子:

var 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 个步骤,检查此

于 2012-11-29T10:32:16.447 回答