javascript - 在 Javascript 中设置日期格式

标签 javascript date datetime format

我必须在某个文件中记录我的日期时间错误,因为我使用以下代码:

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

根据上面的代码输出如下,这很好,但没有按照我需要的格式:

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

我想要结果如下:

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

请参阅“,”之前的日期部分。我需要10 月 10 日声明10 月 10 日

这可以通过一些函数来完成,该函数是字符串中前 4 个字符的子字符串并再次在第三个位置连接,但我仍然很好奇是否有其他简单的方法可以做到这一点?我不想使用任何第三方库/脚本。

谢谢。

最佳答案

您可以尝试向原型(prototype)添加扩展方法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

关于javascript - 在 Javascript 中设置日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26294089/

相关文章:

html - 不使用 javascript 确定用户代理时区偏移量?

javascript - ffmpeg 错误 : Can't make thumbnail from video in javascript

javascript - Check Box在gridview中以行索引方式被选中

javascript - 更新变量的值

javascript - 函数在 http 触发时超时

javascript - 如何计算从今天起30天后的日期

javascript - 如何将日期从 2018-04-29 格式转换为 29 Apr,2018 格式?

c# - 日期转换: From LINQ to JSON to Javascript

date - 使用 clj-time 按区域设置确定日期格式

Python 时间日期匹配