javascript date variable formatting - chrome vs safari - javascript

I'm querying vimeo's API to get the uploaded date of my videos. I'm wondering why this works in chrome, but not safari, and what the proper way to create a time stamp for this video is:
var vimeoDate = videos[i].upload_date;
var vidDate = new Date(videos[i].upload_date);
var vidTime = vidDate.getTime();
console.log('vimeoDate: ' + vimeoDate + ', ' + vidDate + ', ' + vidTime);
//returns: "vimeoDate: 2012-06-07 13:47:08, Invalid Date, NaN"
You can see a JSFiddle which returns invalid date here:
http://jsfiddle.net/nPSqL/
To simplify this, you can simply take this string: and run it in safari and it fails:
console.log(new Date('2013-01-02 13:33:51'));
http://jsfiddle.net/nPSqL/1/

Hmm
new Date('2012-06-07 13:47:08'); // works
therefore your given parameter must actually have type date. Because the console prints the date. If it's a date then you are trying to do something like that:
var date = new Date();
new Date(date); // doesn't work
And that doesn't work.
To check if your variable is of type date try this:
var isDate = function(date) {
return Object.prototype.toString.call(date) === "[object Date]";
};
Ok, found solution:
http://jsfiddle.net/nPSqL/2/
Got it from new Date() using Javascript in Safari

Related

Why does Ionic-2 Calendar gives "Invalid Date" after passing to js Date() and when calling onViewTitleChanged?

I am trying to figure out why I keep getting an "Invalid Date" after passing it to var sDate = new Date(title). My goal is to only get the current month, so I could query it on sqlite.
Using ionic 4, ionic2-calendar and angular on ionic-cordova.
I have the following ionic2-calendar method.
onViewTitleChanged(title)
{
console.log("onViewTitleChanged:")
console.log(title)
var sDate = new Date(title)
console.log("check Date:")
console.log(sDate)
console.log("typeof:")
console.log(typeof title);
}
Which outputs the following.
onViewTitleChanged:
May 2020
check Date:
Invalid Date
typeof:
string
I tried to run a single file date.js and tried to run on node.
node date.js
And gives the following output.
sDate:
2020-04-30T16:00:00.000Z
I also tried to run a code-snippet, works fine. But on the ionic-device, it does not?
var title = "May 2020"
console.log("onViewTitleChanged:")
console.log(title)
var sDate = new Date(title)
console.log("check Date:")
console.log(sDate)
console.log("typeof:")
console.log(typeof title);
I could not get why it does not work on the emulator (iOS), debugging using Safari nor the device.
This is what I did to resolve my issue. Thanks for the suggestion that I should pass a valid ISO 8601 on Safari.
My solution was just to split the passed Month and Year and re-formatted it.
// Passed Month, Year Only
var title = "May 2020"
// Split Ionic Month and Year
var sd = title.split(" ")
// Format to Proper Date
var pd = sd[0] + ' 1, ' + sd[1]
var sDate = new Date(pd)
console.log("Proper Date Parsed:")
console.log(sDate)
var month = '0' + (sDate.getMonth() + 1);
var year = sDate.getFullYear();
console.log("Month(slice):" + month.slice(-2))
console.log("Year(slice):" + year)
Works now.

Not able to split a string in Node.js

I am trying to send a request to node server. The browser sends the date in mm/dd/yyyy format which is handled by server in the below manner.
var endDate;
if (req.query.endDate) {
endDate = new Date(req.query.endDate);
}
This works just fine in chrome and other browsers except IE.
In IE11, it encodes the date to '?5?/?24?/?2017' from '5/24/2017' for some reason.
To fix this I am trying to do this :
var endDate;
if (req.query.endDate) {
endDate=req.query.endDate.toString().trim();
endDate=endDate.toString().split('?').join('');
console.log('Log',endDate);
endDate = new Date(endDate);
}
Expected result is '5/24/2017' But it does not work.
When i see the split('?') for '?5?/?24?/?2017' in the logs it shows ['?5?/?24?/?2017'] as the result. Why is it not splitting the string?
Am I doing Anything wrong?
Node version : 4.3.2(using NVM)
In your case "?" could be not the question mark, assume, some UTF-8 symbol.
It can be used the date formatting itself:
var endDate = new Date(req.query.endDate);
endDate.toLocaleDateString()
or
var endDate = new Date(req.query.endDate);
(endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
or regexp approach:
req.query.endDate.toString().match(/[0-9]+/g); // [month, date, year]

new Date is not working on Firefox

Can you tell me why this is not working on Firefox (V 34 latest) ? It's working fine on all other browsers. 'DatePosted' is shown as Invalid Date.Why ? Any help would be highly appreciated.
//Get local time for everything:
data.Comments.forEach(function (x) {
x.DatePosted = new Date(x.DatePosted.toString().replace("T", " ") + " UTC");
});
Note : x.DatePosted : "2014-11-18T08:06:39.06"
You dont need to replace the T. It works without it (tested in Chrome and Firefox).
After setting the Date object, get it into UTC.
Working snippet below:
var myDate = new Date("2014-11-18T08:06:39.06");
// now set it to UTC
var myDateinUTC = Date.UTC(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());
console.dir(myDateinUTC);
var myNewDate = new Date(myDateinUTC);
console.log(myNewDate.getMonth()); // just to test

javascript Date object create using string from input

I've got a problem with date object in IE8, and some older browsers. On website I have input hidden, where I keep date, and after change new date should be in that field.
On my machine everything is fine, but on some others I get NaN-NaN-NaN, that's my code:
var date = new Date($('#curDate').val());
//date.setDate(date.getDate() - 7);
var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg);
When I run this file (php), in hidden input I've got Monday's date from the current week 2013-03-25.
This alert return me NaN-N.. on Win XP IE8, and on very old mac, I recon it's problem with object. How to take date value and convert it to object in javascript?
Never use new Date(some_string) - it's unreliable because it depends on the user's locale.
Break the string into its yy/mm/dd components yourself and then call new Date(y, m - 1, d)
Problem with your hyphens..
Convert your hyphens('-') with slashes('/')
var dateStr=$('#curDate').val();
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
or
var date=new Date(convertToSlash($('#curDate').val()));
function convertToSlash(string){
var response = string.replace(/-/g,"/");
return response;
}
You can also use new Date(some_string) format. It's reliable. However, the datestring must be in ISO format that is yyyy/mm/dd.

Javascript JSON Date parse in IE7/IE8 returns NaN

I'm parsing a date from a JSON event feed - but the date shows "NaN" in IE7/8:
// Variable from JSON feed (using JQuery's $.getJSON)
var start_time = '2012-06-24T17:00:00-07:00';
// How I'm currently extracting the Month & Day
var d = new Date(start_time);
var month = d.getMonth();
var day = d.getDate();
document.write(month+'/'+day);// "6/24" in most browsers, "Nan/Nan" in IE7/8
What am I doing wrong? Thanks!
In older browsers, you can write a function that will parse the string for you.
This one creates a Date.fromISO method- if the browser can natively get the correct date from an ISO string, the native method is used.
Some browsers got it partly right, but returned the wrong timezone, so just checking for NaN may not do.
Polyfill:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Result:
var start_time = '2012-06-24T17:00:00-07:00';
var d = Date.fromISO(start_time);
var month = d.getMonth();
var day = d.getDate();
alert(++month+' '+day); // returns months from 1-12
For ie7/8 i just did:
var ds = yourdatestring;
ds = ds.replace(/-/g, '/');
ds = ds.replace('T', ' ');
ds = ds.replace(/(\+[0-9]{2})(\:)([0-9]{2}$)/, ' UTC\$1\$3');
date = new Date(ds);
This replaces all occurrences of "-" with "/", time marker "T" with a space and replaces timezone information with an IE-friendly string which enables IE7/8 to parse Dates from Strings correctly. Solved all issues for me.
See RobG's post at Result of toJSON() on a date is different between IE8 and IE9+.
Below function worked for me in IE 8 and below.
// parse ISO format date like 2013-05-06T22:00:00.000Z
function convertDateFromISO(s) {
s = s.split(/\D/);
return new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
}
You can test like below:
var currentTime = new Date(convertDateFromISO('2013-05-06T22:00:00.000Z')).getTime();
alert(currentTime);
I suggest http://momentjs.com/ for cross browser date issues.
#gib Thanks for the suggestion on Moment.js. This small library really helps out with dealing with dates and JavaScript.
Moment.js solved the problem described in the original question that I was also having. IE8 was displaying JSON ISO dates as NaN when parsed into a new Date() object.
Quick solution (include moment.js in your page, or copy the code to your js functions include)
If you just need to display a date on your page, loaded from a JSON ISO date, do this:
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.calendar()); //use Moment's relative date function to display "today", "yesterday", etc.
or
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.format('m/d/YYYY')); //use Moment's format function to display "2/6/2015" or "10/19/2014", etc.
If you must have a Date() object (say for use with jQuery Components), do the following so successfully populate your JSON provided ISO date. (This assumes you are already inside the function of handling your JSON data.)
var ship_date = new Date(moment(data.ShipDate).format('m/d/YYYY')); //This will successfully parse the ISO date into JavaScript's Date() object working perfectly in FF, Chrome, and IE8.
//initialize your Calendar component with the "ship_date" variable, and you won't see NaN again.

Categories