开发者

Regex needed for parsing a date/time string

Can someone provide me with a regex for the following? (Using Javascript)

source string: Jan 2 2开发者_开发问答010 6:00PM

I want the resulting string to show only the time, as shown below. (example above used)

result string: 6:00 PM


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.


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.


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.


You could use SimpleDateFormat with the format MMM dd yyyy HH:mm. Then you can get the time part.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜