Rahul Pamnani
Rahul Pamnani

Reputation: 1435

My selected date is showing one day before in Ionic 4

I am working in my Ionic 4 app and I have used a native datepicker for that and I am converting the date to toISOString() but the problem is that it is showing one day before.

This is my ts:

this.datePicker.show({
  date: new Date(),
  mode: 'date',
  androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK,
}).then(
  date => {
    me.acceptchallengeform.setValue({
      startchallenge: new Date(date).toISOString().split('T')[0], 
    });
    console.log('Got date: ', date)},
  err => {
    console.log('Error occurred while getting date: ', err)}
);

var DatePickerDate ='Thu Aug 09 2018 00:00:00 GMT+0100 (British Summer Time)';

var myDate = new Date(DatePickerDate).toISOString().split('T')[0];

so myDate is now 2018-08-08

The problem is that it is showing the date one day before.

But I want to show the exact selected date.

Any help is much appreciated.

Upvotes: 0

Views: 819

Answers (2)

Rahul Pamnani
Rahul Pamnani

Reputation: 1435

Try This:

date = new Date(date.setDate(date.getDate() + 1));
me.acceptchallengeform.setValue({
   startchallenge: new Date(date).toISOString().split('T')[0], 
});

This will solve your problem.

Upvotes: 0

Cyril Hanquez
Cyril Hanquez

Reputation: 698

new Date() return the date using your system timezone.

toISOString() return the date in UTC and the time part of your date is midnight, so it returns Thu Aug 08 2018 23:00:00 (BST - 1h), that's why you're getting one day before.

What are your trying to do exactly?

Editing my answer following comment

  • in your case I would choose the easy way as you apparently don't need any timezone information:

    startchallenge: date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

Upvotes: 1

Related Questions