Javascript date returning NAN in IE8 - javascript

I am trying to parse date like this 2012-12-07T16:18:15+05:30 which I am receiving from database in string format.
The parse function I am using is:
var jstime = new Date("2012-12-07T16:18:15+05:30");
var h = jstime.getHours();
var m = jstime.getMinutes();
var s = jstime.getSeconds();
var f = "am"
if(h >= 12)
{
f = "pm";
h = h - 12;
}
if(h == 0)
{
h = 12;
}
var str;
str = jstime.toDateString();
str = str +"," + h.toString() + ":" + m.toString() + ":" + s.toString() + " " + f.toString();
However,IE8 browser returning NAN at very first line i.e. jstime is NAN in IE8,while working fine in other browsers.
so, Is there any alternate way to parse date that works well in all browsers?
I need it accepts date in above format & returns date in format:
Fri Dec 07 2012,4:18:15 pm?

If you can be sure of the format, you can regex it:
var match = "2012-12-07T16:18:15+05:30".match(/(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)([+-])(\d\d):(\d\d)/);
var jstime = new Date();
jstime.setUTCFullYear(parseInt(match[1],10));
jstime.setUTCMonth(parseInt(match[2],10)-1);
jstime.setUTCDate(parseInt(match[3],10));
jstime.setUTCHours(parseInt(match[4],10)-parseInt(match[7]+"1",10)*parseInt(match[8],10));
jstime.setUTCMinutes(parseInt(match[5],10)-parseInt(match[7]+"1",10)*parseInt(match[9],10));
jstime.setUTCSeconds(parseInt(match[6],10));
But if it's coming from the server-side, you may be able to format it more reliably there.

You can do this -
date = Date.parse("2012-12-07T16:18:15+05:30");
var jstime = new Date(date);
var h = jstime.getHours();
var m = jstime.getMinutes();
var s = jstime.getSeconds();
continue your code .....
I think this will help you.

Related

Why do I get an NaN for my first date parse?

I am trying to convert two strings to dates but I am getting an NaN for an obviously date string.
Can anyone tell me why this happens?
Code:
function SortMaster() {
return function (a, b) {
var aValue = a, bValue = b, aLength = a.length, bLength = b.length;
var aType = Object.prototype.toString.call(aValue);
var bType = Object.prototype.toString.call(bValue);
var aasd = Date.parse(aValue);
var basd = Date.parse(bValue);
var aDate = (new Date(Date.parse(aValue))).toISOString().slice(0, 10).replace(/-/g, "");
var bDate = (new Date(Date.parse(bValue))).toISOString().slice(0, 10).replace(/-/g, "");
var highestValue = Math.max(aLength, bLength);
for (var i = 0; i < highestValue; i++) {
}
};
}
The value for a is a date string "21.10.2014 14:52:24"
The value for b is also a date string "04.04.2014 15:04:36"
The problem is that a is in dd.mm.yyyy format, seems like this is not recognizable as date by javascript which expected an mm.dd.yyyy format, so it threw an error because there's not such month as 21, but for b the error passed because the day was 04 which is less than 12 so it considered it as month while in fact it's day, so your format should not be dd.mm.yyyy
to demonstrate it check this jsFiddle
you see a2 is same date as a1 just in mm.dd.yyyy and it worked for a2 but a1 was invalid date
var a1 = '21.10.2014 14:52:24',
a2 = '10.21.2014 14:52:24',
b = '04.04.2014 15:04:36';
var dateA1 = new Date(Date.parse(a1)),
dateA2 = new Date(Date.parse(a2)),
dateB = new Date(Date.parse(b));
console.log('a1:' + dateA1); // error, Invalid Date
console.log('a2:' + dateA2);
console.log('b:' + dateB);
The issue was that the input string have had not the correct date format...
I have now created a function to create a correct format out of a date string.
function editDateString(dateString){
var dateStringSplits = dateString.split(' ');
var firstPart = dateStringSplits[0];
var secondPart = dateStringSplits[1];
var Year = firstPart.split(".")[2];
var Month = firstPart.split(".")[1];
var Day = firstPart.split(".")[0];
var Hour = secondPart.split(":")[0];
var Minute = secondPart.split(":")[1];
var Second = secondPart.split(":")[2];
return newDateString = Year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second;
}
Thanks to Mi-Creativity for his help!!!

convert xml date and time using javascript

I am pulling the some information from a stock feed. the time stamp for last update comes in like this:
2016-02-10 13:32:41
How do I format it to be like:
1:32:41pm
2/10/2016
Here is my variable declaration:
time = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
You could turn the string into a valid javascript date and then use the date methods to display it how you want to. For example to turn it into a javascript date, split it into its parts and then assemble.
var dateAndtime = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
var date = dateAndtime.split(' ')[0];
var time = dateAndtime.split(' ')[1];
var year = date.split('-')[0];
var month = date.split('-')[1]-1;
var day = date.split('-')[2];
var hour = time.split(':')[0];
var minute = time.split(':')[1];
var second = time.split(':')[2];
var d = new Date(year, month, day, hour, minute, second);
There is no need to create a Date, you can just parse and reformat the string. You have to parse the string anyway, reformatting without a Date is just more efficient.
// 2016-02-10 13:32:41 => m/dd/yyyy h:mm:ssap
function reformatDateString(s) {
var b = s.split(/\D/);
var ap = b[3] < 12? 'am':'pm';
var h = b[3]%12 || 12;
return h + ':' + b[4] + ':' + b[5] + ap +
'\n' + +b[1] + '/' + b[2] + '/' + b[0];
}
document.write(reformatDateString('2016-02-10 13:32:41').replace('\n','<br>'))
document.write('<br>');
document.write(reformatDateString('2016-12-09 03:02:09').replace('\n','<br>'))

Converting date format from mm/dd/yyyy to yyyy-mm-dd format after entered

In my datepicker the date will be inserted in mm/dd/yyyy format. But after I inserted I want it to be sent in yyyy-mm-dd format. I am using JavaScript to do this. But I wasn't able to do that. So what should I do?
Thanks & regards,
Chiranthaka
you could also use regular expressions:
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
return dateParts[3] + "-" + dateParts[1] + "-" + dateParts[2];
}
var inDate = "12/06/2013";
var outDate = convertDate(inDate); // 2013-12-06
The expression also works for single digit months and days.
I did the opposite for my website, but it might help you. I let you modify it in order to fit your requierements. Have fun !
getDate
getMonth
getFullYear
Have fun on W3Schools
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
if(curr_month < 10)
curr_month = "0"+curr_month;
if(curr_date < 10)
curr_date = "0"+curr_date;
var curr_date_format = curr_date+"/"+curr_month+"/"+curr_year;
Adding more to Christof R's solution (thanks! used it!) to allow for MM-DD-YYYY (- in addition to /) and even MM DD YYYY. Slight change in the regex.
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})[\/ -](\d{1,2})[\/ -](\d{4})/);
return dateParts[3] + "-" + dateParts[1] + "-" + dateParts[2];
}
var inDate = "12/06/2013";
var outDate = convertDate(inDate); // 2013-12-06
As Christof R says: This also works for single digit day and month as well.
// format from M/D/YYYY to YYYYMMDD
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear();
var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
return "".concat(yyyy).concat(mm).concat(dd);
};
var siku = new Date();
document.getElementById("day").innerHTML = siku.yyyymmdd();

Add time to the date value

I am using a jQuery plugin named mobiscroll to select a date, but the problem is that I also need to add to the result plus 15 minutes.
I have a function p(j), which returns 08/28/2012 12:15 - 12:15 (or only 08/28/2012 12:15 - as convenient), but instead i need 12:15 - 12:30. Are there any ideas?
According to the mobiscroll documentation setDate works with a Date object.
See this link on how to work with date objects in javascript. You don't need to do any string manipulations.
After you have the right date use the .scroller('setDate',newDate,true);
What about string manipulation?
var dateStr = p(j), //08/28/2012 12:15 - 12:15
timeStrSlice = dateStr.split(' ')[1].split(':'),
h = parseFloat(timeStrSlice[0]),
m = parseFloat(timeStrSlice[1]);
var nh = h,
nm = m + 15;
if(nm > 60) {
nh++;
nm = 0;
}
if(nh > 24) {
nh = 0;
}
var result = h + ":" + m + " " + nh + ":" + nm; // 12:15 12:30
Date d = new Date(2012,08,28);
d.setHours(12, 30, 0, 0);
See if this works for you:
var now = new Date();
//add 15 minutes to now
var out = new Date(now).setMinutes(now.getMinutes()+15)

jQuery: Add 4 weeks to date in format dd-mm-yyyy

I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');

Categories

Resources