I am using Ionic 3, Angular 5, and moment-timezone. I have a form input that displays EndTime (in the format of 01:23 AM) and another that display the length (in the format of 01:30 which represents hh:mm) that is calculated from the mentioned EndTime and the StartTime both of which are DateTime values. When the user changes the EndTime I need it to update the length, and when the user updates the length I need it to calculate the end time.

I feel like I am overcomplicating this and making the function too long. Anyway to improve this?

setSessionEndTime() {
  let time = this.sessionForm.controls['sessLength'].value.split(':');
  const endTime = moment(this.startTime).add(time[0], 'hours').add(time[1], 'minutes');
  const newEndTime = (moment(endTime).toISOString());
  this.sessionForm.controls['sessEndTime'].setValue(newEndTime, {emitEvent: false});
  this.endTime = newEndTime;

setSessionLength() {
  const startTime = moment(this.startTime);
  const endTime = moment(this.endTime);
  let totalHours = (endTime.diff(startTime, 'hours'));
  const totalMinutes = endTime.diff(startTime, 'minutes');
  const clearMinutes = totalMinutes % 60;
  // Must check if value is less than 10 and prepend 0 to it otherwise the datetime input doesnt accept the value
  const sessLength: string = (totalHours < 10) ?
                             `0${totalHours}:${clearMinutes}` :
  this.defaultSesLength = sessLength;
  this.sessionForm.controls['sessLength'].setValue(sessLength, {emitEvent: false});
  • 2
    \$\begingroup\$ How are setSessionEndTime and setSessionLength being triggered? \$\endgroup\$
    – Joseph
    Mar 27 '18 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.