Question

The Google Feed API outputs the published date in the format: "13 Apr 2007 12:40:07 -0700".

I wish to change that to the valid HTML5 <time datetime="YYYY-MM-DDThh:mm:ssTZD"> using JS/jQuery.

Is there an easy way? Or a library?

Was it helpful?

Solution 3

In the end I used the formatDate() function found here. The newer JS Toolbox didn't seem to have preserved this function (or at least didn't make it obvious).

var entryDate = new Date(entry.publishedDate); // From Google Feed API
html5date = formatDate(entryDate,'yyyy-MM-ddThh:mm:ss')+entryDate.toString().slice(28,33);

The slicing is to get the timezone, which formatDate didn't seem to support.

Here is the minified function, for preservation:

/*
 * Author: Matt Kruse <matt@mattkruse.com>
 * http://www.mattkruse.com/
 * formatDate (date_object, format)
 * Returns a date in the output format specified.
 * The format string uses the same abbreviations as in getDateFromFormat()
 */
var MONTH_NAMES="January,February,March,April,May,June,July,August,September,October,November,December,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),DAY_NAMES="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",");function LZ(b){return(0>b||9<b?"":"0")+b} function formatDate(b,f){var f=f+"",h="",g=0,e="",c="",e=b.getYear()+"",c=b.getMonth()+1,i=b.getDate(),j=b.getDay(),d=b.getHours(),k=b.getMinutes(),l=b.getSeconds(),a={};4>e.length&&(e=""+(e-0+1900));a.y=""+e;a.yyyy=e;a.yy=e.substring(2,4);a.M=c;a.MM=LZ(c);a.MMM=MONTH_NAMES[c-1];a.NNN=MONTH_NAMES[c+11];a.d=i;a.dd=LZ(i);a.E=DAY_NAMES[j+7];a.EE=DAY_NAMES[j];a.H=d;a.HH=LZ(d);a.h=0==d?12:12<d?d-12:d;a.hh=LZ(a.h);a.K=11<d?d-12:d;a.k=d+1;a.KK=LZ(a.K);a.kk=LZ(a.k);a.a=11<d?"PM":"AM";a.m=k;a.mm=LZ(k);a.s= l;for(a.ss=LZ(l);g<f.length;){e=f.charAt(g);for(c="";f.charAt(g)==e&&g<f.length;)c+=f.charAt(g++);h=null!=a[c]?h+a[c]:h+c}return h};

OTHER TIPS

Check out JavaScript Date Format. (Download here.) Then it's as easy as:

var input = "13 Apr 2007 12:40:07 -0700";
var date = Date.parse(input);
var output = dateFormat(date, 'yyyy-mm-dd"T"hh:MM:ssoD');
// output == 2007-04-13T12:40:07-0700D

Demo here: http://jsfiddle.net/pkC3s/2/

I started a solution for you in pure javascript by extending the Date object. However, I have to run now.

http://jsfiddle.net/2sYut/

Date.prototype.getHtml5String = function(){
    return this.getFullYear() + "-" + this.getMonth() + "-" + this.getDay() + "T" + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds() + "TZ" + this.getTimezoneOffset();
};

var d = new Date( "13 Apr 2007 12:40:07 -0700" );
alert( d.getHtml5String() );

Perhaps you can finish it off (or I will sometime today).

Hope that helps...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top