Parsing Date with javascript in FireFox - javascript

I have strange date format like this dMMMyyyy (for example 2Dec2013).
I'm trying to create Date object in my javascript code:
var value = "2Apr2014";
var date = new Date(value);
alert(date.getTime());
example
in Google Chrome this code works fine but in FireFox it returns Null
Can anyone suggest something to solve this problem
Thanks.

How about just parsing it into the values new Date accepts, that way it works everywhere
var value = "02Apr2014";
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var month = value.replace(/\d/g,''),
parts = value.split(month),
day = parseInt(parts.shift(), 10),
year = parseInt(parts.pop(), 10);
var date = new Date(year, m.indexOf(month), day);
FIDDLE

This fiddle works in both firefox and chrome
var value = "02 Apr 2014";
var date = new Date(value);
alert(date.getTime())
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I would suggest using something like jQuery datepicker to parse your dates.
I haven't tested it but it seems you'd need something like:
var currentDate = $.datepicker.parseDate( "dMyy", "2Apr2014" );
jsFiddle
Just be aware of:
d - day of month (no leading zero)
dd - day of month (two digit)
M - month name short
y - year (two digit)
yy - year (four digit)
However if for some reason you really wanted to do it yourself, then you could check out this link: http://jibbering.com/faq/#parseDate
It has some interesting examples on parsing dates.
Whilst not exactly what you want, the Extended ISO 8601 local Date format YYYY-MM-DD example could be a good indication of where to start:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}

You can use following JavaScript Library for uniform date parser across browser.
It has documentation
JSFIDDLE
code:
var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());

Related

Date calculation - Daylight saving time (DST) and Timezone issue - Turkey

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.

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

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)

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Get day from Date in JavaScript [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks

Categories