JCCV
JCCV

Reputation: 75

How do I get just the date here using Regex?

DATA:

"Sun Sep 30 2012 12:37:24 GMT-0700 (Pacific Daylight Time)"

In Regex, I'm trying to just get "Sep 30 2012" without making a literal /Sep\s\d\d\s2012/

I want to pretty much take out "Sun " and " 12:37:24...." so that only "Sep 30 2012" is captured.

How would I do this in JavaScript REGEX?

UPDATE:

I made one, but it's not that elegant: \w{3}\s\d{1,2}\s2\d\d\d

Is there a REGEX pattern that can say, "take out the first 3 letters and one space after it... capture the date format... don't take anything afterwards."

Upvotes: 0

Views: 115

Answers (5)

João Silva
João Silva

Reputation: 91319

You could just use substring:

var s = "Sun Sep 30 2012 12:37:24 GMT-0700 (Pacific Daylight Time)";
s = s.substring(4, 15); // "Sep 30 2012"

If you really insist on using a regular expression, you could use:

s = s.match(/\w{3}\s(\w{3}\s\d{1,2}\s2\d{3})/)[1]; // "Sep 30 2012"

But quite honestly, dates are not really meant to be parsed with a regular expression, or substring for that matter, but with real Date parsers.

Upvotes: 0

Janus Troelsen
Janus Troelsen

Reputation: 21300

Answering the question "how to say three letters and a space in JS":

> "abc ".match("[A-Za-z]{3} ")
["abc "]
> "ab3 ".match("[A-Za-z]{3} ")
null

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Don't. I can see that you're almost certainly using some JavaScript date-to-string conversion (maybe even just (new Date).toString()) and that is locale-dependent. It will be different for many users of the script.

Instead the date should already be in a specific format. Such as in PHP you can do date("Y-m-d H:i:s") and then use as is or split(/[- :]/). Or if you already have the Date object, just use the get*() functions.

If I am wrong and your format is actually exactly that every time regardless of locale, then I guess something like this would do: /[A-Z][a-z]{2} \d{2} \d{4}/

Upvotes: 1

Anoop
Anoop

Reputation: 23208

You can use split , splice and join

var date = "Sun Sep 30 2012 12:37:24 GMT-0700 (Pacific Daylight Time)" ;
var desiredResult = date.split(" ").splice(1, 3).join(" ");

Upvotes: 1

Marten
Marten

Reputation: 1356

To me it seems that the day and month are always 3 characters long, so the searched string has always the same length and is always at the same position.

"Sun Sep 30 2012 12:37:24 GMT-0700 (Pacific Daylight Time)".slice(4, 15)

Upvotes: 1

Related Questions