can someon开发者_C百科e help me with a javascript regex question? I am trying to replace all the digit dates in a string to a formatted version. This is what I have so far
txt = txt.replace(/\d{10}/g, 'Formatted Date Here');
Is this possible? Any help is greatly appreciated! Thanks!
Try this:
str = str.replace(/\d{10}/g, function($0) {
return new Date($0*1000);
});
Date
accepts a time in milliseconds. That’s why you multiply the match (passed in $0
) with 1000.
If you want a different format than the default format, take a look at the methods of a Date instance. Here’s an example:
str = str.replace(/\d{10}/g, function($0) {
var d = new Date($0*1000);
return (d.getMonth() + 1) + ", " + d.getDate() + ", " + (d.getHours() % 12 || 12) + ":" + d.getMinutes() + " " + (d.getHours() < 12 ? 'AM' : 'PM');
});
The JavaScript Date.format functon Amarghosh posted here might help you.
You can use replace()
with a function callback to achieve this:
var txt = "This is a test of 1234567890 and 1231231233 date conversion";
txt = txt.replace(/\d{10}/g, function(s) {
return new Date(s * 1000);
});
alert(txt);
outputs:
This is a test of Sat Feb 14 2009 07:31:30 GMT+0800 and Tue Jan 06 2009 16:40:33 GMT+0800 date conversion
You will need to adjust this to use the correct date format. Also you will need to consider the issue of time zones. The time zone on the client isn't necessarily the same as that on the server.
You might even be better off formatting the date on the server to avoid such issues.
Are you sure you want to use regex? Here is a JavaScript Date format function that you might want to check out.
精彩评论