0

I am using ionic date time component as below

  <ion-item >
                    <ion-label>Time:</ion-label>
                    <ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" [(ngModel)]="localEstDelTime"></ion-datetime>
              </ion-item>

on ionViewDidLoad i am setting the value of localEstDelTime as:

var d = new Date()
 var dt = d.setTime(d.getTime() + (5.5 + 2)*60*60*1000)
this.localEstDelTime = dt.toISOString()

basically 5.5 hours has been added to make it for indian time zone which is GMT + 5.5 and for this use case the time is supposed to be shown plus 2 hours of current time.

now, the requirement is let's say end user added another extra hour through UI then i want to get that hour and time in the local time zone. My code does not work properly as below:

 var storeEstDelTime =  Date.parse(this.localEstDelTime)
 var date = new Date(storeEstDelTime)
 var hours = date.getHours() + 5.5
 var minutes = date.getMinutes()

        var ampm = Number(hours) >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour ’0′ should be ’12′
        var minutesStr = Number(minutes) < 10 ? '0'+ minutes : minutes;

        estDeliveryTime = hours + ':' + minutesStr + ' ' + ampm;

so i need estDeliveryTime to be just hh:mm AM/PM format. my above code need to be fixed.

Vik
  • 8,721
  • 27
  • 83
  • 168

2 Answers2

0

It is always a good idea to convert your date to UTC time set always as it is a common standard. Like for input date, just convert the date like this:

var now = new Date(),
    utcDate = new Date(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(), 
        now.getUTCSeconds()
    );

Now, when you take input from user for delivery time(for that extra hour), do the same thing to that date, and add that hour to the utcDate and in the end, convert the UTC date to GMT date with 5.5 as for IST.

Hope this helps:)

saberprashant
  • 388
  • 5
  • 15
0
  1. npm i --save date-fns

  2. import {format} from "date-fns" in your .ts file

  3. let example_time = "2019-11-30T14:42:30.951+08:00";

  4. format(new Date(example_time), "HH:mm");

  5. console.log(example_time) => '14:42'