Parsing a Youtube API Date in Javascript - javascript

Youtube's API returns a JSON object with an array of videos. Each video object has a published date formatted like "2012-01-11T20:49:59.415Z". If I initialize a Javascript Date object using the code below, the object returns "Invalid Date".
var dt = new Date( "2012-01-11T20:49:59.415Z" );
I'm using this on iOS/mobile Safari, if that makes a difference.
Any suggestions or ideas on how to create a valid object?

Try using JavaScript's Date.parse(string) and the Date constructor which takes the number of milliseconds since the epoch. The "parse" function should accept a valid ISO8601 date on any browser.
For example:
var d = new Date(Date.parse("2012-01-11T20:49:59.415Z"));
d.toString(); // => Wed Jan 11 2012 15:49:59 GMT-0500 (EST)
d.getTime(); // => 1326314999415

var dt = "2012-01-11T20:49:59.415Z".replace("T"," ").replace(/\..+/g,"")
dt = new Date( dt );

I ended up finding a solution at http://zetafleet.com/blog/javascript-dateparse-for-iso-8601. It looks like the date is in a format called 'ISO 8601.' On earlier browsers (Safari 4, Chrome 4, IE 6-8), ISO 8601 is not supported, so Date.parse doesn't work. The code referenced from the linked blog post extends the current Date class to support ISO 8601.

If you only need a portion of the date (eg. if you don't care about the time or time zone) you can just strip that portion of the date string off.

This page has code that parses youtube (ISO 8601) dates into a date object:
http://webcloud.se/log/JavaScript-and-ISO-8601/
Archive.org backup of same
It work for me, though I haven't tested it very much.

Related

How can I convert this string representing a Date into an ISO 8601 compliant using JS?

I am not so into JavaScript and I have the following problem.
I have a JSON object like this:
{
"start_date": "2017-11-09 06:00:00"
}
Into a JavaScript script executed into the browser I do:
var dateCurrentOriginalForecast = new Date(currentOriginalForecast.start_date);
and it works fine: it creates a new Date object with the value related to 2017-11-09 06:00:00 date.
The problem is that I have to perform this JavaScript script into a Java application using Rhino (a JavaScript implementation that allows to perform JS code into a Java application) and here it cause an error:
TID: [-1234] [] [2017-11-09 11:10:08,915] INFO {org.apache.synapse.mediators.bsf.ScriptMessageContext} - dateCurrentOriginalForecast: Invalid Date {org.apache.synapse.mediators.bsf.ScriptMessageContext}
TID: [-1234] [] [2017-11-09 11:10:08,918] ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} - The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: RangeError: Date is invalid. (<Unknown Source>#137) in <Unknown Source> at line number 137
at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)
at javax.script.CompiledScript.eval(CompiledScript.java:92)
It seems that this date is invalid and it can't create the Date object.
From what I understood reading online the problem should be that old JS or Rhino (maybe the version of JS implemented by Rhino) does not support date of this type and probably I have to convert it in a date format which is fully compliant with ISO 8601
So I think that I have to convert my string 2017-11-09 06:00:00 into something like compliant with ISO 8601 standard.
I can't use third party library.
How can I do it?
Can use Date#toISOString() or Date#toJSON()
let d = new Date('2017-11-09 06:00:00')
console.log(d.toISOString())
console.log(d.toJSON())
//if you want convert date without convert in timezone than
var date = '2017-11-09 06:00:00';
var convertDate = date.replace(" ", "T"); // 2017-11-09T06:00:00
//if you want to convert in date with utc timezone
var date = new Date("2017-11-09 06:00:00").toISOString()
If I've understood your question correctly the problem is not so much that you need a ISO 8601 formatted date, but it is that you need to create a Date object from a date that is not formatted in ISO 8601. I personally would just use regular expression to parse the date into it's parts and then pass them into the Date constructor:
var currentOriginalForecast = {
"start_date": "2017-11-09 06:00:00"
};
var rxParseDate = /(\d{4})-(\d\d)-(\d\d)\s+(\d\d):(\d\d):(\d\d)/;
var dateParts = currentOriginalForecast.start_date.match(rxParseDate);
var year = dateParts[1],
month = dateParts[2],
day = dateParts[3],
hour = dateParts[4],
minute = dateParts[5],
second = dateParts[6];
var dateCurrentOriginalForecast = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
console.log(dateCurrentOriginalForecast);
Since there is no timezone mentioned in the start_date, I'm assuming it is UTC and converting it using Date.UTC and passing the resulting timestamp from that into the Date constructor. If start_date is in local time you would just remove Date.UTC and pass the parameters directly into the Date constructor. I'll also mention the month - 1; that is because the Date constructor (and Date.UTC) expect a 0-based month.

Weird ISO formatted Datestring to Javascript Date

I've got a Datestring like this one: 20171010T022902.000Z and I need to create Javascript Date from this string. new Date('20171010T022902.000Z') would return Invalid Date.
I saw that it's possible to use moment.js for this purpose but I am not sure how I would specify the according format for my given example. I found this example from another thread:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');
var jsDate = momentDate.toDate();
Question:
How can I create a JavaScript date from a given Datestring in this format: 20171010T022902.000Z (using moment)?
Your input (20171010T022902.000Z) matches known ISO 8601 so you can simply use moment(String) parsing method. In the Supported ISO 8601 strings section of the docs you will find:
20130208T080910.123 # Short date and time up to ms
Then you can use toDate() method
To get a copy of the native Date object that Moment.js wraps
Your code could be like the following
var m = moment('20171010T022902.000Z');
console.log( m.format() );
console.log( m.toDate() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Note that this code does not shows Deprecation Warning (cited in Bergi's comment) because you input is in ISO 8601 known format. See this guide to know more about this warning.
Moreover "By default, moment parses and displays in local time" as stated here so format() will show the local value for your UTC input (20171010T022902.000Z ends with Z). See moment.utc(), utc() and Local vs UTC vs Offset guide to learn more about moment UTC mode.
I think you can do this without moment.js,.
Basically extract the parts you need using regex's capture groups, and then re-arrange into a correct format for new Date to work with.
var dtstr = '20171010T022902.000Z';
var dt = new Date(
dtstr.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\.\d{3}Z)$/,
"$1-$2-$3T$4:$5:$6$7"));
console.log(dt);
console.log(dt.toString());
If you are using moment.js anyway, this should work ->
var dt = moment("20171010T022902.000Z", "YYYYMMDDTHHmmss.SSSSZ");
console.log(dt.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Javascript datetime parsing from string

I am trying to parse a string to javascript Date object, I tried different ways to parse it to Date but none of them seems to work. Initially I was thinking it will be easy to parse string to Date as JavaScript Date has constructor that takes a string or I would use Date.parse() method but it seems that I was wrong.
Here is string for date format-
2015-12-01 00:28:28.1271204 +01:00
What I have tried so far-
var dateCalc = new Date(str);
var dateCalc = Date.parse(str);
Please this JSFiddle - http://jsfiddle.net/D7c28/12/
Please suggest solution for this. Please let me know if I am missing something.
Thanks :)
It works fine for me:
var str = "Fri, 15 Nov 2013 09:00:00 -0600"
var date = new Date(str);
console.log(date.getDate()) // 15
date is a Date object with many methods like getDate(). Check out the documentation.
Update:
2015-12-01 00:28:28.1271204 +01:00 seems not to be a valid date for the default constructor (but works fine in node on my Mac). So I use moment.js and it works fine.
Check out the updated jsfiddle.
I'm almost sure that
var dateString = "2015-12-01 00:28:28.1271204 +01:00";
var dateCalc = new Date(dateString);
Will work (dateCalc) will have a proper date (that is, Tue Dec 01 2015 00;28:28 GMT+0100.
If you want to be a more flxeible with the solution you always can try MomentJS which gives you a lot of possibilties with format, localization and such stuff.

Unable to parse the date

I'm trying to parse the date which is in the following format
dateFormat: "d-M-y" // returns 10-Oct-13
I'm using jQuery UI for formatting date.
Below is my code:
var d1 = new Date("10-Oct-13");
alert(d1); //Invalid in FF and IE, works in chrome
Seems weird, here is my JSFiddle for reproducing the bug in FF and IE.
Note: I don't want to use plugin, since it is working chrome.
Please share your thoughts.
You can use Datepicker's parseDate() method in conjunction with the format string to parse the date:
var d1 = $.datepicker.parseDate("d-M-y", $("#lastAssimilationDate").val())
alert(d1); // alerts: Thu Oct 10 2013 00:00:00 GMT+0200
See the edited JSFiddle.
From the MDN doc for Date:
dateString
String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).
Essentially you're passing a string in an unsupported date format as the dateString parameter of the constructor, so the JavaScript engine is (correctly) stating that it's an invalid date. Chrome seems to be slightly more forgiving with the date formats it allows, but that's non-standard.
You can use the getDate function to obtain a Date object representing your selected date:
var d1 = $('#lastAssimilationDate').datepicker("getDate");
Use the built-in getDate method:
$('button').click(function(){
var d1 = $("#lastAssimilationDate" ).datepicker('getDate');
console.log(d1);
});
You can also assign an altField with an altFormat of yyyy-mm-dd if you need to send an ISO-standard date to the server.

date object returns different date when parsing using D3.time.format

var startDate = new Date('2013-05-13');
var date_format = d3.time.format("%m/%d");
if I do
startDate = date_format(startDate);
I get "05/12" instead of "05/13". Anyone has a clue why is this happening?
Don’t use the Date(string) constructor to parse dates; it varies from browser to browser. The most likely (but not guaranteed) interpretation of "2013-05-13" is as an ISO8601 string in UTC time. Thus, if you run your statement in the JavaScript console, you will see:
> new Date("2013-05-13")
Sun May 12 2013 17:00:00 GMT-0700 (PDT)
The string is interpreted in UTC time by the Date construct, while the returned Date object is in local time. May 13, midnight UTC is May 12 5PM PDT, so when you format it in local time using d3.time.format, you get back May 12.
You could switch to using d3.time.format.utc("%m/%d") to format your date, but then you’re still dependent on the ambiguous behavior of the Date(string) constructor. So, instead…
As #minikomi suggested, you could create a d3.time.format to parse a date string: d3.time.format("%Y-%m-%d"), then format.parse("2013-05-13"). Or you could use the multi-argument Date constructor: new Date(2013, 4, 13), but note that months start at zero rather than the usual one.
You might get more consistent results using a d3.time.format to parse your string as well:
var startDate = '2013-05-13';
var parser = d3.time.format("%Y-%m-%d");
var formatter = d3.time.format("%m/%d");
var startDateString = formatter(parser.parse(startDate));

Categories