2

I am just trying to achieve a simple thing, to get the current date as "dd-mm-yyyy" or "mm-dd-yyyy", so am using this:

var date = new Date();
$("#datefield").val(date.toLocaleDateString());

in IE it's giving the date using this format: "Day, Month d, yyyy" in Chrome it's giving the date using this format: "m/d/yyyy"

How can I achieve the format that I need for all browsers?

David Hemsey
  • 277
  • 3
  • 11

1 Answers1

3

You could always use a library, or a jQuery plugin. Otherwise, your best option is to format the date yourself. It's guaranteed cross-browser.

var date = new Date();
var str =
    ('0' + date.getDate()).slice(-2) + '-' +
    ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
    date.getFullYear();
// $("#datefield").val(str);    

alert(str);

Here ('0' + something).slice(-2) is used to pad day and month with a 0, if necessary.

Months in JavaScript are counted from 0 to 11, that's why date.getMonth() + 1.

The rest of the code is self-explanatory I think.

Community
  • 1
  • 1
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • Thanks @GOTO , what libraries can I use to easily format the date? What way do people use in their projects? – David Hemsey Sep 06 '15 at 12:27
  • @DavidHemsey Well, the top voted answer in the post I linked to suggests using [jQuery UI](https://jqueryui.com). That's a pretty common extension in projects that already use jQuery. You could give it a try. – GOTO 0 Sep 06 '15 at 12:54
  • Thanks GOTO, I have just tried the plugin, it doesn't work in IE, and in chrome it's giving wrong value when using: $.format.date(new Date(),"mm/dd/yy"); Any ideas? – David Hemsey Sep 06 '15 at 21:23
  • @DavidHemsey Not sure, but the syntax should be `$.datepicker.formatDate('dd-mm-yy', new Date())`. Does this work? – GOTO 0 Sep 06 '15 at 21:36
  • it gives me: Cannot read property 'formatDate' of undefined in chrome – David Hemsey Sep 06 '15 at 21:48
  • @DavidHemsey Make sure you are including the correct versions of jQuery and jQuery UI. This works in Chrome: https://jsfiddle.net/pz5nLL6L/ – GOTO 0 Sep 06 '15 at 21:55
  • @DavidHemsey Feel free to post your complete HTML file if you can't get it to work. – GOTO 0 Sep 06 '15 at 21:56
  • Oh, we were on 2 different pages. I was using the jQuery format library you posted its link in your answer – David Hemsey Sep 06 '15 at 21:59
  • Is it the same one as : https://jqueryui.com/ I can't find the documentation for the validation – David Hemsey Sep 06 '15 at 22:01
  • @DavidHemsey Ok... sorry, maybe I was not clear enough. Don't know about the other library, but the documentation for the jQuery UI function is here: https://api.jqueryui.com/datepicker/#utility-formatDate – GOTO 0 Sep 06 '15 at 22:10