jQuery invalid date error - javascript

Why is the first date invalid? I don't understand.
https://jsfiddle.net/r4dgjdn6/1/
$(document).ready(function() {
alert(new Date('19.12.2016 14:00'));
alert(new Date('12.12.2016 14:00'));
});
I want to calculate date difference but i keep getting the Invalid Date error.

You can use the library http://momentjs.com/ and use it like this:
var a = moment('19.12.2016 14:00', 'DD.MM.YYYY mm:ss');
var b = moment('12.12.2016 14:00', 'DD.MM.YYYY mm:ss');
//to calculate the diff
a.diff(b);

because the 'date' constructor can get specific "date format" as parameters
for example :
alert(new Date('Mon Dec 19 2016 14:00:00'));
take a look at this :
http://www.w3schools.com/js/js_dates.asp
EDIT:
if it is always in this format you can use this "quick" code to parse your string into the right format:
var inputString = '19.12.2016 14:00';
var tmpArray = inputString.split('.');
var result = tmpArray[1] + "-" + tmpArray[0] + "-" + tmpArray[2].split(' ')[0] + " " + tmpArray[2].split(' ')[1];
alert(new Date(result));

Related

Javascript Date String returns invalid Date

I am trying to convert a date string into a date object within javascript. My date has the following format:
"13.02.2015 12:55"
My current approach was:
var d = new Date("13.02.2015 12:55");
But this didnt work and always returns invalid date. If I enter a date as "12.02.2015 12:55" it works in chrome but not in firefox.
I guess this is because he thinks the first part is the month, but in germany this is not the case.
How can I get this to work?
use moment.js:
var date = moment("13.02.2015 12:55", "DD.MM.YYYY HH.mm").toDate();
Update 2022-05-28:
Meanwhile the project status of moment.js has changed. Therefore I strongly suggest to read https://momentjs.com/docs/#/-project-status/ and observe the recommendations.
try the ISO 8601 format,
or better yet, read this http://www.ecma-international.org/ecma-262/5.1/#sec-15.9
Edit: if you have no other choice than to get it in that format though, i guess you'll need something like this:
function DDMMYYYY_HHMMtoYYYYMMDD_HHMM($DDMMYYYY_HHMM) {
var $ret = '';
var $foo = $DDMMYYYY_HHMM.split('.');
var $DD = $foo[0];
var $MM = $foo[1];
var $YYYY = $foo[2].split(' ') [0].trim();
var $HH = $foo[2].split(' ') [1].split(':') [0].trim();
var $MMM = $foo[2].split(' ') [1].split(':') [1].trim();
return $YYYY + '-' + $MM + '-' + $DD + ' ' + $HH + ':' + $MMM;
}
var d=new Date(DDMMYYYY_HHMMtoYYYYMMDD_HHMM('13.02.2015 12:55'));

Leading 0 missing from data and time

I have a function which works well, for converting dates from a webservice returned in json format. The webservices gives dates in the following type of format:
Data example: The dates look like this in the json data
\/Date(1373875200000)\/
Current function: This is the current function I have
function HumanDate(date) {
var jsondateString = date.substr(6);
var current = new Date(parseInt(jsondateString));
var month = current.getMonth() + 1;
var day = current.getDate();
var year = current.getFullYear();
var hour = current.getHours();
var minute = current.getMinutes();
var datetime = day + "/" + month + "/" + year + " " + hour + ":" + minute
return datetime;
}
Usage: This is how I use the function above
success: function(data) {
if (data.d[0]) {
$.each(data.d, function(index, data) {
$("body").append(HumanDate(data.from) + '<br />');
});
} else {
Current output: This is the output I currently get, notice the missing 0's
2/7/2013 9:0
15/7/2013 9:30
15/10/2013 10:0
15/11/2013 10:30
Expected output: This is the output I would like, notice the extra 0's
02/07/2013 09:00
15/07/2013 09:30
15/10/2013 10:00
15/11/2013 10:30
Question:
How do I get the date and time formatted as the Expected output examples?
If you don't use a library, then you have to do some work, that is you have to put the "0" yourself.
Instead of simply concatenating day, you need to concatenate
(day<10 ? '0'+day : day)
and the same for the other fields.
But note that there are good javascript libraries filling this kind of gap. I personally used datejs for date manipulations.
I'd suggest using a library for this kind of thing -- something like Moment.js would do the job perfectly (and give you a load more functionality like date addition/subtraction into the bargain).
With moment.js, your code could look like this:
function HumanDate(date) {
return moment(date).format('MM/DD/YYYY HH:mm');
}
usage example:
alert(HumanDate("\/Date(1373875200000)\/"));
//alerts "07/15/2013 09:00"
Hope that helps.
You could also try moment.js. A 6.5kb library for formatting dates
var m = moment( new Date() );
m.format( "DD/MM/YYYY HH:mm");

Get GMT String from current Date

I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library
date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.
The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n) { return n < 10 ? '0'+n : n }
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() +1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

How to format a date pulled from a form field with javascript

I have a date picker that generates a date like 6/30/2012 in a form field.
I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.
var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);
and then use to generate the date.
datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]
The problem is it gived me the date 2012-6-30 instead of 2012-06-30.
Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?
The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.
To format your example:
var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');
Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy
http://archive.plugins.jquery.com/project/jquery-dateFormat
try this, hope this help:
Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012
important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!
something on the line of this:
function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}
Based on your example, a simple function is:
var formatUStoISOdate = (function() {
function aZ(n) {
return (n<10? '0' : '') + n;
}
var re = /[^0-9]/;
return function(d) {
var d = d.split(re);
return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);
// or
// return [d[2], aZ(d[0]), aZ(d[1])].join('-');
}
}());
alert(formatUStoISOdate('3/31/2011')); // 2011-03-31

JavaScript Date getTime() inconsistent

I'm trying to implement a parser for the tablesorter plugin for jQuery and I have this strange behaviour with the getTime() value for dates. The following code:
var dateOne = '03/04/2010';
var dateTwo = '28/10/2008';
var dateOneTime = new Date(dateOne).getTime();
var dateTwoTime = new Date(dateTwo).getTime();
var diff = dateOneTime - dateTwoTime;
alert('dateOneTime: ' + dateOneTime + '\ndateOne: ' + dateOne + '\nDateTwoTime: ' + dateTwoTime + '\ndateTwo : ' + dateTwo + '\none - two: ' + diff);
Gives a getTime() result for the 2010 date as 1267 billion or so, and for the 2008 date 1271 billion. Therefore subtracting dateTwo from dateOne gives a negative number. Why is this? Surely the dateTwo value, being in 2008, should be smaller?
Date expects MM/DD/YYYY
You are passing in DD/MM/YYYY
By default, the format is mm/dd/yyyy. Thus, 28/10/2008 is being interpreted as 04/10/2010.
When you initialize a date in JS via a string, it should be an RFC1123-compliant format - yours aren't.
new Date(dateTwo) is being interpreted incorrectly as April 10 2010 because the Date constructor is expecting MM/DD/YYYY instead of the DD/MM/YYYY you are passing.
try
var dateOne = '04/03/2010';
var dateTwo = '10/28/2008';

Categories