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.
Related
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]
Date calculation issue in JavaScript on Browser. There are 3 parameters -
From Date, No. of days & To Date
From Date selected using calendar component in JavaScript = 30/10/2016
No. of days entered = 2
Based on no. of days entered "To Date" should be calculated, so as per above input of From date & No. of days calculated "To Date" value should be 01/11/2016 but due to some wrong calculation it's showing 31/10/2016.
Time Zone - Istanbul, Turkey
Please refer below image for code snipped -
As it is clear from code snipped that prototype JavaScript library being used.
dateUtil.prototype.addDays=function(date,noofDays)
{
var _dateData=date.split("/");
var _date=eval(_dateData[0]);
var _month=eval(_dateData[1]);
var _year=eval(_dateData[2]);
var newFormatedDate = new Date(""+_month+"/"+_date+"/"+_year);
var newAddedDate=newFormatedDate.getTime() + noofDays*24*60*60*1000;
var theDate = new Date(newAddedDate);
var dd = theDate.getDate();
var mm = theDate.getMonth()+1; // 0 based
if(mm<10)
mm="0"+mm;
var yy = theDate.getYear();
if (yy < 1000)
yy +=1900; // Y2K fix
var addedDate=""+dd+"/"+mm+"/"+yy;
return addedDate;
}
It seems noofDays*24*60*60*1000 logic is problem where DST is not being considered.
There are 2 timezone showing with the same code but with different date format.
Please could you advise any guidance or read-up on this.
Edit :
JavaScript code added.
Probably not worth posting the code since it has some fundamental errors that should not have survived the new millennium.
var _date = eval(_dateDate[0]);
Don't use eval. There are a small number of cases where it is appropriate, but in general, just don't use it. Ever. The above is the same as:
var _date = _dateDate[0];
Then there is:
var newFormatedDate = new Date('' + _month + '/' + _date + '/' + _year)
You started on the right track by avoiding parsing strings with the Date constructor by splitting the date string into it's parts. But then you undid that good work by creating a new string and parsing it with Date. Just use parts directly:
var newFormatedDate = new Date(_year, _month-1, _date)
which removes all the vagaries of Date parsing and is less to type as well. Also, Date objects don't have a format, so a name like date is fine.
To add n days, just add them to the date:
var date = new Date(_year, _month-1, _date)
date.setDate(date.getDate() + 2);
So your function can be:
function dateUtil(){}
/* Add days to a date
** #param {string} date - date string in dd/mm/yyyy format
** #param {number} noofDays - number of days to add
** #returns {Date}
*/
dateUtil.prototype.addDays = function(date, noofDays) {
var dateData = date.split('/');
var date = new Date(dateData[2], dateData[1] - 1, dateData[0]);
date.setDate(date.getDate() + +noofDays);
return date;
}
var d = new dateUtil();
console.log(d.addDays('23/09/2016',3).toLocaleString());
I've use +noofDays to ensure it's a number. Also, the SO console seems to always write dates as ISO 8601 strings in Z time zone so I've used toLocaleString to keep it in the host time zone.
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)
How can I convert a UTC time into proper date - time format using Javascript?
This is what I want to do
var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
// return "2014-01-01" // how can i get this?
}
Now How, can i get orignal date - 2014-01-01 from 1388534400000?
****Also, Please note that when i do this --- new Date(1388534400000); it gives date 1 day less.
That is, instead of giving Jan 01 2014, it gives Dec 31 2013. But, I want Jan 01 2014.****
Is there any method to do the opposite of toUTC() method?
// _________ For those whose toUTC() doesnt work
"toUTC" method works in console of my chrome
See screen shot below
When you pass a string containing hyphens to the Date constructor, it will treat that as UTC. And if you don't pass a time, it will consider it to be midnight. If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion.
Here's a screenshot of my chrome dev console, so you can see what I mean
If I pass slashes instead:
Consider using moment.js - which will accept a format parameter that will help you avoid this issue.
Try using the following:
new Date(new_d);
The problem lies with the way you instantiate the Date.
Javascript interpretes the hyphens as an utc date, and slashes as local dates.
Giving the results that mark Explains.
var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date
But to translate a date back to your starting point string, you can do the following.
function toDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getDate();
m = date.getMonth() +1;
y = date.getFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
function addLeadingZero(n, length){
n = n+'';
if(n.length<length)
return addLeadingZero('0'+n, length--);
else
return n;
}
If you find yourself with a UTC date, you can still do this:
function toUTCDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getUTCDate();
m = date.getUTCMonth() +1;
y = date.getUTCFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
To play around with it, and see it for yourself, see this Fiddle:
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.