Reputation: 28783
I'm using AJAX to pull in an RSS feed and show a list of items. However the date that comes back is super long and needs to be shorter.
e.g. Mon, 11 Jun 2012 17:53:35 PDT
to become just 11 Jun 2012 17:53
Is it possible to do this with javascript?
The code looks like this currently:
for(var i = 0; i < feed.items.length && i < 5; i++) {
var item = feed.items[i];
html += '<li>'
+ item.updated;
html += ' | <span class="title">'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</span></li>';
}
So I need to do something to that item.updated
object.
I've done a quick search on parsing dates, but not found anything I can make use of.
Upvotes: 0
Views: 106
Reputation: 12420
You can use this RegEx:
var result = "Mon, 11 Jun 2012 17:53:35 PDT".replace(
/[A-Z][a-z]{2}, (\d+) ([A-Z][a-z]{2}) (\d+) (\d+):(\d+):\d+ [A-Z]{3}/,
"$1 $2 $3 $4:$5"
); // result = "11 Jun 2012 17:53"
Or even simpler:
var result = "Mon, 11 Jun 2012 17:53:35 PDT".replace(
/[A-Z][a-z]{2}, (\d+ [A-Z][a-z]{2} \d+ \d+:\d+):\d+ [A-Z]{3}/,
"$1"
); // result = "11 Jun 2012 17:53"
Even more simpler:
var result = "Mon, 11 Jun 2012 17:53:35 PDT".match(
/(\d+ [A-Z][a-z]{2} \d+ \d+:\d+)/
)[0]; // result = "11 Jun 2012 17:53"
But if you care about timezones, i.e. want to display the client's timezone instead, you can do this:
var Result = new Date("Mon, 11 Jun 2012 17:53:35 PDT").toString().match(
/([A-Z][a-z]{2} \d+ \d+ \d+:\d+)/
)[0]; // result = "Jun 12 2012 08:53" // client's timezone, GMT+8 for example
Upvotes: 1
Reputation: 48793
var longdate = "Mon, 11 Jun 2012 17:53:35 PDT";
var shortdate = datestr.match(/\d[^:]*:\d\d/)[0];
// -> "11 Jun 2012 17:53"
Upvotes: 2
Reputation: 816364
Looks like you could just strip everything before the first white space and after the last colon. That is easy with indexOf
[docs], lastIndexOf
[docs] and substr
[docs]:
date = date.substr(date.lastIndexOf(':')).substr(0, date.indexOf(' '));
Of course you'd have to adjust this if the format changes.
Upvotes: 1