使用javascript格式化DATE(可能正则表达式) [英] Format a DATE with javascript (maybe regex)
问题描述
我正在使用JavaScript和JQuery,我有一个像这样的字符串(不可更改的xml响应):
I'm using JavaScript and JQuery and I've got a string like this (unchangeable xml response):
var str = "2017-01-08T16:06:52+00:00";
如何转换为这样的日期:
How can I convert to a Date like this:
08 january 2017, 16:06:52
或者至少:
08 01 2017, 16:06:52
我试图使用 .replace()
,如:
str = str.replace(/(\d{4})-(\d{2})-(\d{2})T(\d{8}).*/,'$2 $3 $1, $4');
但它不起作用。 :(
But it doesn't works. :(
推荐答案
为此,你可以创建一个 Date()
来自字符串的对象,然后将 Date()
对象公开的方法中的字符串连接在一起。试试这个:
To do this you can create a Date()
object from the string, then concatenate together a string from the methods the Date()
object exposes. Try this:
var str = "2017-01-08T16:06:52+00:00";
var date = new Date(str);
var months = [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" ];
var dateString = ("00" + date.getDate()).slice(-2) + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ', ' + ("00" + date.getHours()).slice(-2) + ':' + ("00" + date.getMinutes()).slice(-2) + ':' + ("00" + date.getSeconds()).slice(-2);
console.log(dateString);
请注意,这可以更简单b使用日期格式库(例如MomentJS或DateJS)但是包括整个库来格式化单个日期是相当浪费的。如果您需要在整个网站中反复执行此操作,那么它们可能是值得的。
Note that this can be made simpler by using a date formatting library (such as MomentJS or DateJS) however including an entire library to format a single date is rather wasteful. If you need to do this repeatedly throughout your site then they may be worth it.
另请注意,在英语国家/地区,月份名称应大写,因此请考虑修改该案例的格式。
Also note that in English speaking countries the month names should be capitalised, so consider amending the format for that case.
这篇关于使用javascript格式化DATE(可能正则表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!