Reputation: 2176
Can someone provide me with a regex for the following? (Using Javascript)
source string: Jan 2 2010 6:00PM
I want the resulting string to show only the time, as shown below. (example above used)
result string: 6:00 PM
Upvotes: 0
Views: 4676
Reputation: 50349
If you need to convert it into a date object, and if you're using Javascript in a web browser, you might want this instead:
new Date('Jan 2 2010 6:00PM'.replace(/(?=[AP]M)/i, ' '));
// Sat Jan 02 2010 18:00:00 GMT-0600 (Central Standard Time)
new Date('Jan 2 2010 6:00PM'.replace(/(?=[AP]M)/i, ' ')).toUTCString();
// Sun, 03 Jan 2010 00:00:00 GMT
Mozilla has reference documentation on the Javascript Date object.
Upvotes: 0
Reputation: 59451
Replace (\d{1,2}:\d{1,2})([AP]M)
with \1 \2
Update: Use \d{2}
instead of \d{1,2}
if the source string is guaranteed to be in the HH:MM
format.
Upvotes: 6
Reputation: 41097
You could use SimpleDateFormat
with the format MMM dd yyyy HH:mm
. Then you can get the time part.
Upvotes: 0
Reputation:
Implementing SilentGhost's comment in regex: /([^ ]+)([^ ]{2})$/
This will match the last space-delimited "word", with the first bit in group 1 and the last two chars in group 2. The translation to string operations instead should be straight-forward.
You could also replace the (..)
with [AP]M
or similar, if desired, and might benefit from a tiny bit of validation if you construct the regex to prevent something like blah blah haha-I-gave-garbage-inputPM
, but there are many ways to deal with garbage anyway.
Upvotes: 1
Reputation: 196
While I haven't looked I'm sure you'll be able to find something that will work for you at the Regex Library website. However I happen to agree with SilentGhost in that it might be easier to just split the string. Just make sure all DateTimes are are in the same format.
Upvotes: 0