new Date is not working on Firefox - javascript

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

Related

Datepicker date is not being set through jQuery code

Hello all I am trying to set date of datepicker control in jQuery. When I run the page through Mozilla Firefox browser it works fine. However, when I run it in Google Chrome the date is not being set. Does anybody know what the problem is?
cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
var myDate = new Date(cookie_value);
var date1 = new Date(Date.parse(myDate));
date1.setDate(date1.getDate());
var newDate = date1.toDateString();
newDate = new Date(Date.parse(newDate));
var option = "minDate";
$("#ctl00_ContentPlaceHolder1_txtArrivalDate").datepicker("option", option, newDate);
// $("#ctl00_ContentPlaceHolder1_txtArrivalDate").datepicker("option", option, newDate);
$("#ctl00_ContentPlaceHolder1_txtDepartureDate").datepicker('setDate', newDate);
Much of your code seems redundant. Why do date1=new Date(....) and then date1.setDate(...)? Why create newDate if it is just a copy of date1?
See:
http://jsfiddle.net/QB6K6/
It works in chrome for me using the code below. Depends on the value of your cookie, though.
$(document).ready(function () {
var cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
var myDate = new Date(cookie_value);
$("#ctl00_ContentPlaceHolder1_txtArrivalDate").datepicker( {minDate:myDate});
$("#ctl00_ContentPlaceHolder1_txtDepartureDate").datepicker();
$("#ctl00_ContentPlaceHolder1_txtDepartureDate").datepicker("setDate", myDate);
});

Why JavaScript's Date object is invalid in Firefox?

I have date in a div which looks like "30-Apr-2013" and I want to convert it to: 30 Tuesday
APR | 2013
I have write some code to make this conversion for me. Its working fine in Chrome but some how its not working in Firefox and in firebug console it says: Date {Invalid Date} and shows output looks like NaN undefined undefined | NaN. My code looks is below or you can also see this Fiddle:
(function ( $ ) {
$.fn.bcDateModify = function() {
return this.each(function() {
var obj = this;
var srcDate= $(obj).html();
srcDate = srcDate.replace(/\s+/g, '');
objDate = new Date(srcDate);
console.log(objDate);
var newDate = objDate.getDate();
var newDay = objDate.getDay();
var newMonth = objDate.getMonth();
var newYear = objDate.getFullYear();
var weekday=new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var monthNames=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var myhtml ='<div class="date"><span>'+newDate+'</span></div><div class="month-day"><h3>'+weekday[newDay]+'</h3><span>'+monthNames[newMonth]+' | '+newYear+'</span></div>';
$(obj).html(myhtml);
});
};
}( jQuery ));
$(document).ready(function(){
$('.date-obj').bcDateModify();
});
You cannot construct a date the way you are (at least in Firefox you can't), for example passing in the string "22-Jul-2013".
I changed this line
objDate = new Date(srcDate);
to
var dateSplit = srcDate.split("-");
objDate = new Date(dateSplit[1] + " " + dateSplit[0] + ", " + dateSplit[2]);
to ensure the date was constructed correctly.
See the updated fiddle here.
Just found this item regarding the usage of dates with hyphens in FF. Seems like none of the FF versions support that format.
One possible alternate is to replace the - with a prior to constructing the date.
srcDate = srcDate.replace(/-/g, ' ');
This solution works cross browser and has been tested in Firefox v19, Chrome v24 and Safari v5.1.7 (on Windows).
Demo
I know this likely isn't the best answer but I have found these types of things to be really tricky cross browser. This small library has saved me a ton of time.
http://momentjs.com/
moment("30-Apr-2013", "DD-MMM-YYYY").format("DD dddd MMM | YYYY");
Honestly I feel like JavaScript should have this stuff built in like PHP or other languages.

CDate for Javascript

I have been using CDate in my program and the worry part is , it works only in IE.
cdate(strValue) . If I pass the value of strvalue as 01/02 , it returns as Wed Jan 2 etc . Am looking for the same implementation in javascript so that it will work in other browsers. Am trying my best to find one, but am not lucky. Can anyone tell me what api we can use in javascript instead of using CDate ??
You can try the following code:
var comp = "05/04".split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var date = new Date(null, m - 1, d);
date.toDateString(); //this line will return the date
Now you can parse the string and manipulate string according to your need.

javascript date variable formatting - chrome vs safari

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

Date parsing in javascript is different between safari and chrome

I have the following code
var c = new Date(Date.parse("2011-06-21T14:27:28.593Z"));
console.log(c);
On Chrome it correctly prints out the date on the console. In Safari
it fails. Who is correct and more importantly what is the best way
to handle this?
You can't really use Date.parse. I suggest you use: new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
To split the string you could try
var s = '2011-06-21T14:27:28.593Z';
var a = s.split(/[^0-9]/);
//for (i=0;i<a.length;i++) { alert(a[i]); }
var d=new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
alert(s+ " "+d);
My similar issue was caused by Safari not knowing how to read the timezone in a RFC 822 time zone format. I was able to fix this by using the ISO 8601 format. If you have control of the date format I got this working with java's SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ss.sssXXX" which produces for me ie. "2018-02-06T20:00:00.000+04:00". For whatever reason Safari can't read "2018-02-06T20:00:00.000+0400", notice the lack of colon in the timezone format.
// Works
var c = new Date("2018-02-06T20:00:00.000+04:00"));
console.log(c);
// Doesn't work
var c = new Date("2018-02-06T20:00:00.000+0400"));
console.log(c);
I tend to avoid Date.parse, as per the other answers for this question. It doesn't seem to be a portable way to reliably deal with dates.
Instead, I have used something like the function below. This uses jQuery to map the string array into a number array, but that's a pretty easy dependency to remove / change. I also include what I consider sensible defaults, to allow you to parse 2007-01-09 and 2007-01-09T09:42:00 using the same function.
function dateFromString(str) {
var a = $.map(str.split(/[^0-9]/), function(s) { return parseInt(s, 10) });
return new Date(a[0], a[1]-1 || 0, a[2] || 1, a[3] || 0, a[4] || 0, a[5] || 0, a[6] || 0);
}
I've checked it in several browsers, and yes, safari returns invalid date. By the way, you don't have to use Date.parse here, just new Date([datestring]) will work too. Safari evidently requires more formatting of the datestring you supply. If you replace '-' with '/', remove the T and everything after the dot (.593Z), it will give you a valid date. This code is tested and works in Safari
var datestr = '2011-06-21T14:27:28.593Z'.split(/[-T.]/);
var safdat = new Date( datestr.slice(0,3).join('/')+' '+datestr[3] );
Or using String.replace(...):
new Date("2016-02-17T00:05:01+0000".replace(/-/g,'/').replace('T',' ').replace(/(\..*|\+.*/,""))
I use the following function for parsing dates with timezone. Works fine both Chrome and Safari:
function parseDate(date) {
const parsed = Date.parse(date);
if (!isNaN(parsed)) {
return parsed;
}
return Date.parse(date.replace(/-/g, '/').replace(/[a-z]+/gi, ' '));
}
console.log(parseDate('2017-02-09T13:22:18+0300')); // 1486635738000 time in ms
I ended up using a library to offset this:
http://zetafleet.com/blog/javascript-dateparse-for-iso-8601
Once that library was included, you use this code to create the new date:
var date = new Date(Date.parse(datestring));
Our project wasn't using millisecond specifiers, but I don't believe that will cause an issue for you.
Instead of using 'Z' at the end of the date string, you can add the local client timezone offset. You'll probably want a method to generate that for you:
let timezoneOffset = () => {
let date = new Date(),
timezoneOffset = date.getTimezoneOffset(),
hours = ('00' + Math.floor(Math.abs(timezoneOffset/60))).slice(-2),
minutes = ('00' + Math.abs(timezoneOffset%60)).slice(-2),
string = (timezoneOffset >= 0 ? '-' : '+') + hours + ':' + minutes;
return string;
}
So the end result would be:
var c = new Date("2011-06-21T14:27:28.593" + timezoneOffset());
Here is a more robust ISO 8601 parser than what others have posted. It does not handle week format, but it should handle all other valid ISO 8601 dates consistently across all browsers.
function newDate(value) {
var field = value.match(/^([+-]?\d{4}(?!\d\d\b))(?:-?(?:(0[1-9]|1[0-2])(?:-?([12]\d|0[1-9]|3[01]))?)(?:[T\s](?:(?:([01]\d|2[0-3])(?::?([0-5]\d))?|24\:?00)([.,]\d+(?!:))?)?(?::?([0-5]\d)(?:[.,](\d+))?)?([zZ]|([+-](?:[01]\d|2[0-3])):?([0-5]\d)?)?)?)?$/) || [];
var result = new Date(field[1], field[2] - 1 | 0, field[3] || 1, field[4] | 0, field[5] | 0, field[7] | 0, field[8] | 0)
if (field[9]) {
result.setUTCMinutes(result.getUTCMinutes() - result.getTimezoneOffset() - ((field[10] * 60 + +field[11]) || 0));
}
return result;
}
console.log(newDate('2011-06-21T14:27:28.593Z'));
console.log(newDate('1970-12-31T06:00Z'));
console.log(newDate('1970-12-31T06:00-1200'));
Use this to both (Safari / Chrome):
Date.parse("2018-02-06T20:00:00.000-03:00")
i tried converted date by truncating it and parsing it like that , its working fine with safari and ios .
var dateString = "2016-01-22T08:18:10.000+0000";
var hours = parseInt(dateString.split("+")[1].substr("0","2"));
var mins = parseInt(dateString.split("+")[1].substr("2"));
var date = new Date(dateString.split("+")[0]);
date.setHours(date.getHours()-hours);
date.setMinutes(date.getMinutes()-mins);
Instead of using a 3rd party library, this is my - relatively simple - solution for this:
function parseDateTime(datetime, timezone) {
base = new Date(datetime.replace(/\s+/g, 'T') + 'Z');
hoursUTC = base.toLocaleTimeString('de-AT',{ timeZone: 'UTC' }).split(':')[0];
hoursLocal = base.toLocaleTimeString('de-AT',{ timeZone: 'Europe/Vienna' }).split(':')[0];
timeZoneOffsetSign = (hoursLocal-hoursUTC) < 0 ? '-':'+';
timeZoneOffset = Math.abs(hoursLocal-hoursUTC);
timeZoneOffset = timeZoneOffsetSign + timeZoneOffset.toString().padStart(2, '0') + ':00';
return new Date(datetime.replace(/\s+/g, 'T') + timeZoneOffset);
}
localDate = parseDateTime('2020-02-25 16:00:00','Europe/Vienna');
console.log(localDate);
console.log(localDate.toLocaleString('de-AT','Europe/Vienna'));

Categories