1

I am using vue3-datepicker library.

      <datepicker  
      v-model="to_date"
      inputFormat="yyyy-MM-dd"
       />

My data method is below:

data(){
    to_date: new Date(),
}

When I am selecting a date and printing {{this.to_date}}, it is printing in Fri Sep 17 2021 09:39:49 GMT+0530 (India Standard Time).

I want it in yyyy-MM-dd format.

How can I achieve this?

Hemant Sah
  • 333
  • 5
  • 12
  • You need to format the date. https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date#34015511 – Arkar Aung Sep 17 '21 at 04:26
  • Well it's working but results only with slashes yyyy/mm/dd, I went through [toLocaleDateString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) doc, but didn't find anything. – Hemant Sah Sep 17 '21 at 04:55

2 Answers2

0

A quick solution is to use Date.prototype.toISOString(), which formats the date as:

yyyy-MM-ddTHH:mm:ss.sssZ

So you get the desired date format by splitting the result by T, and taking the first array element:

const formatDate = date => {
  const tzOffset = date.getTimezoneOffset() * 60 * 1000
  return new Date(date - tzOffset).toISOString().split('T')[0]
}

Then use the method in your template:

<span>{{ formatDate(to_date) }}</span>

demo

tony19
  • 125,647
  • 18
  • 229
  • 307
0

You can achieve using moment npm package

install:-

npm i moment

example:-

moment(new Date()).format("yyyy-MM-dd")

you can use Use different format

var dt = new Date();

console.log(moment(dt).format("YYYY-MM-DD HH:mm:ss"));
console.log("Date: "+moment(dt).format("YYYY-MM-DD"));
console.log("Year: "+moment(dt).format("YYYY"));
console.log("Month: "+moment(dt).format("MM"));
console.log("Month: "+moment(dt).format("MMMM"));
Archin Modi
  • 492
  • 1
  • 8
  • 19