1

I'm using mydatepicker in my Angular application. When user clicks a specific date I'm getting the selected date. But I want to have a date format like this.

20180320

or

2018-03-20

So what I did was to convert as follows.

onDateChange(event) {
    this.selectDate = event.jsdate.toISOString().slice(0,10)
}

This helps me to get my format. But it shows a day before. That means , if a user selects 2018-03-20 from calendar my selectDate = 2018-03-19

I can do that using moment , but for this project I'm not using for some reasons.Could someone help me to correct this?

Salman A
  • 262,204
  • 82
  • 430
  • 521
apple_92
  • 263
  • 2
  • 7
  • 17
  • 2
    You are probably having issues with the timezone. Check that the calendar timezone matches your own timezone. – yBrodsky Mar 26 '18 at 17:05

3 Answers3

1

Try this to account for timezone

onDateChange(event){
    var localDate =  new Date(event.jsdate.getTime() - event.jsdate.getTimezoneOffset() * 60000);
    this.selectDate = localDate.toISOString().slice(0,10);
}
Matt
  • 2,096
  • 14
  • 20
  • This works. Can you plz explain this? – apple_92 Mar 26 '18 at 17:39
  • it basically creates a new date that adjust for timezone offset, so when you call `toISOString()` it will give you the local datetime instead of the UTC datetime – Matt Mar 26 '18 at 18:03
0

toISOString is always in UTC+0 time. If you console.log it, you should see a Z on the end. That means GMT.

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

ecg8
  • 1,362
  • 1
  • 12
  • 16
0

Just try this with prototype function

Date.prototype.getDDMMYYYY = function () {
    var date = JSON.stringify(this.getDate()).length == 1 ? ("0" + this.getDate()) : this.getDate();
    var month = JSON.stringify(this.getMonth()).length == 1 ? ("0" + this.getMonth()) : this.getMonth();
    var year = this.getFullYear();
    return  year+"-"+month+"-"+date;
}

and Just replace this code

onDateChange(event){
   this.selectDate = event.jsdate.getDDMMYYYY()
}
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29