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!!!
Related
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>'))
Objective: Setup the date in the array at the end of the block to read: yyyymmdd including the zeros. (example data build: numDaysAPITimes = [20150403]). What I got is not getting the month correctly and the numDaysAPITimes array is storing only the year for some reason.
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date(backDateEpochTime); //Convert to UTC
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
numDaysAPITimes[i] = (curr_year + curr_month + curr_date);
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
a couple things:
your date info is getting added together as numbers, that why it seems the year is only going through. One way to handle that would be to use the toString() method.
you'll probably want leading zeroes on the day and month, which you can achieve by prepending a 0 and then doing a slice -2.
That would looks like This JSFiddle, or:
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = 2;//document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date((1000*backDateEpochTime)); //Convert to UTC
var curr_date = ("0" + d.getDate()).slice(-2)
var curr_month = ("0"+ (d.getMonth() + 1)).slice(-2); //Months are zero based
var curr_year = d.getFullYear();
console.log(d.getMonth());
numDaysAPITimes[i] = (curr_year.toString() + curr_month.toString() + curr_date.toString());
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
console.log(numDaysAPITimes)
I'm trying to convert date format (DD-MM-YYYY) to (YYYY-MM-DD).i use this javascript code.it's doesn't work.
function calbill()
{
var edate=document.getElementById("edate").value; //03-11-2014
var myDate = new Date(edate);
console.log(myDate);
var d = myDate.getDate();
var m = myDate.getMonth();
m += 1;
var y = myDate.getFullYear();
var newdate=(y+ "-" + m + "-" + d);
alert (""+newdate); //It's display "NaN-NaN-NaN"
}
This should do the magic
var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");
Don't use the Date constructor to parse strings, it's extremely unreliable. If you just want to reformat a DD-MM-YYYY string to YYYY-MM-DD then just do that:
function reformatDateString(s) {
var b = s.split(/\D/);
return b.reverse().join('-');
}
console.log(reformatDateString('25-12-2014')); // 2014-12-25
You can use the following to convert DD-MM-YYYY to YYYY-MM-DD format using JavaScript:
var date = "24/09/2018";
date = date.split("/").reverse().join("/");
var date2 = "24-09-2018";
date2 = date.split("-").reverse().join("-");
console.log(date); //print "2018/09/24"
console.log(date2); //print "2018-09-24"
You just need to use return newdate:
function calbill()
{
var edate=document.getElementById("edate").value;
var myDate = new Date(edate);
console.log(myDate);
var d = myDate.getDate();
var m = myDate.getMonth();
m += 1;
var y = myDate.getFullYear();
var newdate=(y+ "-" + m + "-" + d);
return newdate;
}
demo
But I would simply recommend you to use like #Ehsan answered for you.
First yo have to add a moment js cdn which is easily available at here
then follow this code
moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');
// will return 2020-01-13
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.
JavaScript Check Date not today or in the past.
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > getDate()) {
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}
I cannot change the format coming in.
Looks like you 99% have it. Here it is with a modified if condition:
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > (new Date().getTime())) {
...
}
Update this line:
// Get current date and time
var today = new Date();
// strip time to compare to the parse date
if (x.getTime() > new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime()) {
// this date has not happened yet.
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}
Try to put in constructor the number of month
Instead of string .
Instead of June put 6.