Google Feed API date to HTML5 datetime - javascript

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?

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...

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};

Related

How do show my javascript date object in users local time, across various browsers?

I have a project where Im reading JSON data and it contains a date string that Im getting in the following syntax:
2015-09-16T10:00:00
I need to take that string and make it a date object and have it be in the format MM/DD/YYYY hh:mm:ss and make sure its in the viewing users timezone automatically
I have the following function so far, but the issues I see are that
1.) I have to add the 'T' between the date and time in my string or firefox and IE9 tells me NaN and the date object I'm creating ISN'T A VALID DATE. (not sure why, but OK, I can live with adding the 'T')
2.) The bigger issue/problem: Firefox currently has this working and it shows the correct time for my time zone (10:00:00)... but in IE9, chrome and safari, it shows 6:00:00.
Question: How do I get the final output date string to ALWAYS be in the correct time (based on users time zone) across browsers without need of an external library?
Heres the function in its current state:
function cleanDateTime(thisdt) {
var d = new Date(thisdt) // CONVERT THE PASSED STRING TO A DATE OBJECT
var cleanedDate = '';
// GET ALL THE DATE PARTS...
var MM = (d.getMonth()+1).toString();
var DD = d.getDate().toString();
var YYYY = d.getFullYear().toString();
var hh = d.getHours().toString();
var mm = (d.getMinutes()<10?'0':'').toString() + d.getMinutes().toString();
var ss = (d.getSeconds()<10?'0':'').toString() + d.getSeconds().toString();
// BUILD THE FINAL DATE STRING FROM THOSE PARTS...
var cleanedDate = ( MM + '/' + DD + '/' + YYYY + ' ' + hh + ':' + mm + ':' + ss )
return cleanedDate;
};
and I call this function like so...
console.log ( cleanDateTime('2015-09-16T10:00:00') );
** UPDATE / PROBLEM SOLVED ( Thanks achan )...
As suggested, Im now using moment.js and I call the function like so to have it show correct time across browsers:
console.log ( cleanDateTime(moment("2015-09-16T10:00:00")) );
You will have to manually split the datestring and pass the individual parts of the date to the Date constructor and make any timezone adjustments in the process, again, manually. Or use moment.js as achan suggested in the comments.
var ds = '2015-09-16T10:00:00';
var dsSplit = ds.split('T');
var dateArr = dsSplit[0].split('-');
var timeArr = dsSplit[1].split(':');
var yr = dateArr[0], mon = dateArr[1], day = dateArr[2];
var hr = timeArr[0], min = timeArr[1], sec = timeArr[2];
var date = new Date(yr, mon, day, hr, min, sec);
There are a number of issues here. Firstly, never pass strings to the Date constructor because its parsing of strings is unreliable to day the least. The string "2015-09-16T10:00:00" is treated as follows:
In ECMA-262 ed 3 parsing is entirely implementation dependent, early versions of IE will not parse ISO 8601 format dates
In ES5, it will be treated as UTC
In ECMAScript 2015, it will be treated as local (which is also consistent with ISO 8601)
So unless you want to leave it to chance, always manually parse date strings.
Given that you can be sure that the string is a valid date, parsing it per ECMAScript 2015 only requires a couple of lines of code. The following functions create a Date based on either UTC or local time, depending on which you want. Of course it's pretty easy to make them one function with a toggle that looks for a trailing Z and uses UTC.
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a local date time
**/
function parseISODateLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISODateLocal('2015-09-16T10:00:00') + '<br>');
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a UTC date time
**/
function parseISODateUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseISODateUTC('2015-09-16T10:00:00'));
Presenting a date as 9/6/2015 10:00:00 on the web is likely to be very confusing for many since the vast majority of the world's population will expect the order to be day, month, year. Far better to use an unambiguous format using the month name like September 6, 2015 or 6-Sep-2015 or similar.
this is how i did mine...
var d, m, day, yr;
d = new Date();
day = d.getDate();
m = d.getMonth();
yr = d.getFullYear();
document.getElementById("dateObj").value = m + "/" + day + "/" + yr;
thanks for your vote..
momentjs.org
this is also my favorite javascript library (underscore)

Common FormatDate function for different date formats

Am formatting the Date Format in JavaScript with the below code
function changeDateFormat(date) {
var fromJSON = new Date(parseInt(date.replace(/(^.*\()|([+-].*$)/g, '')));
return fromJSON.getMonth() + 1 + "/" + fromJSON.getDate() + "/" + fromJSON.getFullYear() + " " + fromJSON.getHours() + ":" + fromJSON.getMinutes();
}
i have 2 scenarios where i call the function with 2 diferent parameters
if date = "/Date(1374145967638)/" am getting the correct o/p
if date = "7/18/2013 4:28:52 PM" am getting Jan 01 1970
Is there a way i can write a common function in javascript/Jquery to handle both the dates ?
Am looking for an option without any JQUERY Plugins.
Thanks
I think you can first create a javascript Date object from date string then format it in what ever way you want.
ex:
var date = new Date("7/18/2013 4:28:52 PM");
then you can use different date class methods and format the string manually.

Get GMT String from current Date

I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library
date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.
The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n) { return n < 10 ? '0'+n : n }
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() +1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Date format conversion in JavaScript

I wondering what is the best way to convert a timestamp of this format -
2012-02-18 14:28:32
to a date presentation of this format -
Saturday Feb 2012 14:28:32
Many thanks :)
Javascript date functions are pretty bad... You have the option to convert to UTC http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toutcstring
But if it was me, i would look into Datejs: http://www.datejs.com/ best javascript date api for me
Please take a look at the getting started with Datejs: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
You must first define an array of the English words (Sunday, Monday, Feb, Mar, etc.):
var daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
monthsOfYear = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
To be able insert the extra 0 at the beginning of the minutes and seconds, define a padding function for the String prototype:
String.prototype.padLeft = function(padString,length){
var toReturn = String(this);
while(toReturn.length < length){
toReturn = padString + toReturn;
}
return toReturn;
}
Format the date and time like this:
var time = new Date(), formattedDate, formattedTime, wholeThing;
formattedDate = daysOfWeek[time.getDay()] + ", " + monthsOfYear[time.getMonth()] + " " + time.getDate() + ", " + time.getFullYear();
formattedTime = time.getHours() + ":" + time.getMinutes().padLeft("0",2) + time.getSeconds().padLeft("0",2);
You can get the whole thing by concatenating formattedDate and formattedTime, as in:
wholeThing = formattedDate + " " + formattedTime;
Consider using datejs which is rocks!
var mydate = Date.parse('2012-02-18 14:28:32');
var result = mydate.toString('dddd MMM yyyy h:mm:ss');
console.log(result);
I'd suggest using an external js library to do that. To my understanding, Moment.js is the best date-time conversion library out there.
In this case, it does the job in one line. Just add the moment.js in you project and then do
var timestamp = '2012-02-18 14:28:32';
var formattedTime = moment(timestamp).format('dddd MMM YYYY HH:mm:ss'); // Saturday Feb 2012 14:28:32
JavaScripts Date object is lacking methods for formatting. I would consider using an external library like this one. Seems it has what you're looking for.
try this blog it has enough dateformats:
http://blog.stevenlevithan.com/archives/date-time-format

Javascript date question about format

I've been struggling with javascript more than an hour and came up with a solution - to ask you for help!
A RSS Feed generates the date of every post in this format 2011-05-18T17:32:43Z. How can I make it look like that 17:32 18.05.2011?
Thank you in advance!
Assuming you've parsed the RSS date into a JS Date object (which can be tricky, since many Date.parse implementations don't accept ISO-8601 dates like that)...
//var d=new Date(/*...*/)
// 17:32 18.05.2011
pad(d.getHours())+':'+d.getMinutes()+' '+
pad(d.getDate())+'.'+pad(d.getMonth()+1)+d.getFullYear();
(getMonth returns 0-11 based month)
... you'd also want some kind of zero buffering for the month (in your example) and possibly day, hour (depending)....
function pad(val,len) {
var s=val.toString();
while (s.length<len) {s='0'+s;}
return s;
}
Optionally from string->string you could use:
function reformat(str) {
var isodt=string.match(/^\s*(\-?\d{4}|[\+\-]\d{5,})(\-)?(\d\d)\2(\d\d)T(\d\d)(:)?(\d\d)?(?:\6(\d\d))?([\.,]\d+)?(Z|[\+\-](?:\d\d):?(?:\d\d)?)\s*$/i);
if (isodt===null) {return '';} // FAILED
return isodt[5]+':'+isodt[7]+' '+isodt[4]+'.'+isodt[3]+'.'+isodt[1];
}
You can create a new Date, get the fragments out of it and concatenate everything:
function parse(date) {
var d = new Date(date)
return d.getHours() + ":" + d.getMinutes()
+ " " + d.getDate() + "." + (d.getMonth()+1)
+ "." + d.getFullYear();
}

Categories