views:

46

answers:

3

Hello, can someone 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!

+1  A: 

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.

cletus
Neat, thanks for your response, however I'm still a bit confused on how to implement preg_replace_callback() How would I use it to immediately replace numbers like 18295732 to strings like March 7, 1990
Mark Anderson
javascript built-in replace has allowed a function in the 'replacement' parameter since version 1.3
Jimmy
Thank you very much for your reply, this is a major breakthrough!The digits I would like to convert are in the structure of a php timestamp.
Mark Anderson
A: 

Are you sure you want to use regex? Here is a JavaScript Date format function that you might want to check out.

Amarghosh
+3  A: 

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.

Gumbo
Is there a way that the date could be formatted to say Month, Day, Year, Hour:Min AM/PM ? I'm very confused how multiplying $0 * 1000 arrives at Sat Feb 14 2009 07:31:30 GMT+0800
Mark Anderson
Thank you! The d.getMonth() + 1 threw me off at first because I was unsure why I kept getting 2. This make a lot of sense. Thanks!
Mark Anderson
@Mark Anderson: You should really take a look at the instance methods (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date#Methods_2). They are all explained.
Gumbo