Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date.toString() radix argument error

Why won't the following code output my date to string!?

var d1 = Date.parse('10/29/1990 12:00:00 AM');
console.log(d1.toString('dd/MM/yyyy'));

The error is:

Uncaught RangeError: toString() radix argument must be between 2 and 36

Just trying to format the date...

like image 555
user1477388 Avatar asked Dec 20 '22 05:12

user1477388


2 Answers

Because d1 is not a Date object, but a number. Date.parse returns the milliseconds representation, you will need to feed that into new Date or use the Date constructor directly.

And because JavaScript does not have a native date-formatting function, there are only the implementation-dependent toString and toLocalString and the standardized toISOString and toUTCString (though not supported in older IE). Instead, you will have to do the formatting manually by getting the single components and concatenating them. Luckily, there's a bunch of libaries to help you with that.

like image 173
Bergi Avatar answered Dec 22 '22 18:12

Bergi


The JavaScript Date.prototype.toString method takes no parameters (like formatting and such).

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toString

Using Date.prototype.toLocaleDateString might help: d1.toLocaleDateString('en') works for me, but check out all the fine-print here:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleString

like image 32
freethejazz Avatar answered Dec 22 '22 19:12

freethejazz