如何格式化JavaScript日期?

编程入门 行业动态 更新时间:2024-10-07 22:22:53
本文介绍了如何格式化JavaScript日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何格式化日期,以使闹钟以MM / dd / yyyy格式显示日期?

How do I format this date so that the alert displays the date in MM/dd/yyyy format?

<script type="text/javascript"> var date = new Date(); alert(date); </script>

推荐答案

你原型一个方法,所以你不必这样做再次刺激任务:

You prototype a method so you never have to do this irritating task again:

Date.prototype.toFormattedString = function (f) { var nm = this.getMonthName(); var nd = this.getDayName(); f = f.replace(/yyyy/g, this.getFullYear()); f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2)); f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase()); f = f.replace(/Mmm/g, nm.substr(0,3)); f = f.replace(/MM\*/g, nm.toUpperCase()); f = f.replace(/Mm\*/g, nm); f = f.replace(/mm/g, String(this.getMonth()+1).padLeft('0',2)); f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase()); f = f.replace(/Ddd/g, nd.substr(0,3)); f = f.replace(/DD\*/g, nd.toUpperCase()); f = f.replace(/Dd\*/g, nd); f = f.replace(/dd/g, String(this.getDate()).padLeft('0',2)); f = f.replace(/d\*/g, this.getDate()); return f; };

(是的,你可以链接这些替换,但是在任何人询问之前, )

根据要求,附加的原型支持上述代码段。

As requested, additional prototypes to support the above snippet.

Date.prototype.getMonthName = function () { return this.toLocaleString().replace(/[^a-z]/gi,''); }; //n.b. this is sooo not i18n safe :) Date.prototype.getDayName = function () { switch(this.getDay()) { case 0: return 'Sunday'; case 1: return 'Monday'; case 2: return 'Tuesday'; case 3: return 'Wednesday'; case 4: return 'Thursday'; case 5: return 'Friday'; case 6: return 'Saturday'; } }; String.prototype.padLeft = function (value, size) { var x = this; while (x.length < size) {x = value + x;} return x; };

和使用示例:

alert((new Date()).toFormattedString('dd Mmm, yyyy'));

更多推荐

如何格式化JavaScript日期?

本文发布于:2023-05-28 00:47:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/308251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!