Saj
Saj

Reputation: 317

Jquery new Date - Convert to yyyy-MM-dd and use toLocaleDateString

I have a HTML input box set to type=date

<input name="datereceived" type="date" class="FormDateValues" id="datereceived" />

I want to use Jquery to fill this input box on document load to today's date but because I am in Australia, I have to offset using GMT+10

To get the date, I do the following:

var newDate = new Date();

and then I tried to set the input box using the following:

$('#datereceived').val(newDate.toLocaleDateString());

The browser tells me that for type=date, the format must be set to yyyy-MM-dd and not the Australian time format of dd/MM/yyyy.

I am not sure how to go about enforcing the toLocaleDateString AND converting the date to yyyy-MM-dd.

Upvotes: 5

Views: 25620

Answers (5)

Ali Mousavi
Ali Mousavi

Reputation: 915

With toISOString and slice:

var today = new Date().toISOString().slice(0, 10)
console.log(today)

Upvotes: 3

atiruz
atiruz

Reputation: 2858

Try using fr-CA that returns the format in yyyy-MM-dd.

var yyyymmdd = (new Date ()).toLocaleDateString ("fr-CA");
console.log (yyyymmdd);

Upvotes: 20

Maksym Kozlenko
Maksym Kozlenko

Reputation: 10363

Apart from solution mentined:

If you have jQuery UI loaded:

// jQuery UI datepicker
$.datepicker.formatDate("yy-mm-dd", new Date())

If you have Moment.JS

// Moment JS
moment().format("YYYY-MM-DD")

If you need additional tools for parsing, formatting, comaping dates or converting them between time zones, I recommend to have a look at Moment.js library.

Upvotes: 1

Leon Adler
Leon Adler

Reputation: 3331

If you need the local date (GMT+10 in your case), you need to use methods of Date:

function toHtmlDate (d) {
  return (d.getFullYear() + '-0' + (d.getMonth() + 1) + '-0' + d.getDate()).replace(/-0(\d\d)/g, '-$1');
}

If you need an ISO date (GMT), you can use new Date().toISOString().substring(0, 10). For explanation:

  • Date.prototype.toLocaleDateString output depends on your locale, using string splitting on it might not work for another user
  • Date.prototype.toISOString always returns ####-##-##T##:##:##.###<timezone>, for example 2015-10-18T23:23:22.880Z. Take the first 10 characters, you have <year>-<month>-<date>.

Upvotes: 3

guest271314
guest271314

Reputation: 1

Try using String.prototype.split() , Array.prototype.splice() , Array.prototype.join()

// create array of values returned by `.toLocaleDateString()`,
// delimited by `/`
var d = new Date().toLocaleDateString().split("/"); 
// `y` : year
var y = d.splice(-1)[0];
// set `y` as item at index `0` of `d`
d.splice(0, 0, y);
// join items within `d` with dash character `"-"`
var date = d.join("-");
console.log(date);

Upvotes: 2

Related Questions