简体   繁体   English

用JavaScript格式化日期

[英]Format dates in Javascript

I have to log my error with datetime in some file, for that I am using following code: 我必须在某些文件中记录日期时间错误,因为我正在使用以下代码:

var dLogDate = new Date();
console.log(dLogDate.toString().substring(4) + ', ' + dLogDate.toGMTString().substring(4));

as per above code output comes as follows which is nice but not formated as I need: 按照上面的代码输出如下,这很好,但没有按我的要求格式化:

"Oct 10 2014 12:48:59 GMT+0530 (IST),  10 Oct 2014 07:18:59 GMT"

I want result s follows : 我想要的结果如下:

"10 Oct 2014 12:48:59 (IST),  10 Oct 2014 07:18:59 (GMT)"

see date part before ",". 请参阅“,”之前的日期部分。 I need 10 Oct instated of Oct 10 我需要恢复10月10日10月10日

This can be done with some function which is substring first 4 character from string and concat at 3rd position again, But I am still curious to know if there are any other simple way to do this? 这可以通过某些功能来完成,该功能再次从字符串和concat的第3个位置开始将子字符串的第4个字符作为子字符串,但是我仍然很好奇是否还有其他简单的方法可以做到这一点? I don't want to use any third party library/script. 我不想使用任何第三方库/脚本。

Thanks. 谢谢。

You can use date functions to format date 您可以使用日期函数格式化日期

http://www.w3schools.com/jsref/jsref_obj_date.asp http://www.w3schools.com/jsref/jsref_obj_date.asp

var monthIndex = date.getMonth();

var dayIndex = date.getDay();

var monthArray = ['January',....];

var dayArray = ['Sunday',...]

console.log(monthArray[monthIndex] + "-" + dayArray[dayIndex]);

You could try adding to the prototype an extension method toISTString 您可以尝试向原型添加扩展方法toISTString

function pad(n) {
    return (n < 10) ? '0' + n : n;
}

Date.prototype.toISTString = function(locale) {
    var year = this.getFullYear().toString();
    var month = this.toLocaleString(locale, { month: "short" }) // ECMAScript Internationalization API, which is very new only available in Blink browsers (Chrome and Opera), IE11, and Firefox 29+.
    var day  = this.getDate().toString();
    var hrs = this.getHours().toString();
    var mins = this.getMinutes().toString();   
    var secs = this.getSeconds().toString();
    return day + " " + month + " " + year + " " + pad(hrs) + ":" + pad(mins) + ":" + secs + " (IST)";
};

dLogDate = new Date();
console.log(dLogDate.toISTString("en-us") + ', ' + dLogDate.toGMTString().substring(4));

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM