0
  1. I have got two dropdowns of start time and end time, how to convert it into 24hr format, so that it appears as 07:00..15:00 etc., in the console when selected.

Template

 Start at:
        <select (change)="onSelect($event.target.value)"   id="skill">
         <option value="0" selected>Select</option>
          <option  [value]="i" *ngFor="let type of startTimeArray; let i = index">
            {{type}}
          </option>
       </select>
       End at:
      <select *ngIf="enableEndTime" id="exp">
         <option value="0" selected>Select</option>
          <option [value]="type" *ngFor="let type of tempEndTimeArray">
            {{type}}
          </option>
      </select>

TS

  import { Component } from "@angular/core";
import { FormGroup, FormArray, FormBuilder, FormControl } from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  forTableArray: any = [];
 startTimeArray:any=["07:00 AM","08:00 AM", "09:00 AM", "10:00 AM", "11:00 AM", "12:00 PM",  "1:00 PM",  "2:00 PM", "3:00 PM",  "4:00 PM", "5:00 PM",  "6:00 PM", "7:00 PM", "8:00 PM"];
  endTimeArray:any=["07:00 AM","08:00 AM", "09:00 AM", "10:00 AM", "11:00 AM", "12:00 PM",  "1:00 PM",  "2:00 PM", "3:00 PM",  "4:00 PM", "5:00 PM",  "6:00 PM", "7:00 PM", "8:00 PM"];
  public tempEndTimeArray: Array<any>;
  public enableEndTime: boolean = true;

public onSelect(val){
  console.log(val)
  let index = parseInt(val) + 1;
  console.log(index)
   this.tempEndTimeArray = this.endTimeArray.slice(index);

}
  convertTime12to24(time12h) {
    const [time, modifier] = time12h.split(" ");
    let [hours, minutes] = time.split(":");
    if (hours === "12") {
      hours = "00";
    }
    if (modifier === "PM") {
      hours = parseInt(hours, 10) + 12;
    }
    return `${hours}:${minutes}`;
  }
}

here I have used convertTime12to24 function, but I am not able to send my selected option value to it.

  1. also if I set start date as, say 1PM and end date as 1PM by default (from TS), then it should reflect in the start date, and end date accordingly, and if end dat is 7PM, then the end date array should be between 2PM to 7PM. that is, I am not able to properly populate the vlaues

I want to make my dropdowns work in these two ways, when there is no default value, and when the default value is set

https://stackblitz.com/edit/angular-r2sv3k

rawrstar
  • 165
  • 1
  • 14
  • 2
    Does this answer your question? [convert 12-hour hh:mm AM/PM to 24-hour hh:mm](https://stackoverflow.com/questions/15083548/convert-12-hour-hhmm-am-pm-to-24-hour-hhmm) – Heretic Monkey Apr 09 '20 at 20:43
  • no, I am not getting any value in my console – rawrstar Apr 10 '20 at 11:58
  • Please [edit] your question showing how you attempted to use the code in the answers to that question. – Heretic Monkey Apr 10 '20 at 12:27
  • @HereticMonkey I edited it – rawrstar Apr 10 '20 at 17:18
  • "but I am not able to send my selected option value to it." Well, no, because you are using the index as the value. Use `[value]="type"` on your start selector just like you do on your end selector. Then you can just change `onSelect` to use `console.log(convertTime12to24(val))`. Otherwise, you'll have to do `console.log(convertTime12to24(this.startTimeArray[val[))`. – Heretic Monkey Apr 10 '20 at 17:57
  • @HereticMonkey if it keep [value]="type" , then my slice function on index wont work – rawrstar Apr 13 '20 at 06:52

1 Answers1

0

**

UPDATED ANSWER

**

Here's a StackBlitz that solves your issues now completely. https://stackblitz.com/edit/pm-am-time-conversion

Below I have pasted the whole code but you can find my comments. In summary I implemented the reactive form so I can make things workable. For the editable case, you obviously would be getting data from some server but in order to reproduce it I have just done this to mock: I have taken dates as a class property and In ngOnInit method let { startDate, endDate } = this.dates; and then setting the Form Controls in order to populate the dropdowns.

In the TypeScript file you will see that I am using two generic methods for time conversions:

parseFromAmPmToTwentyFour(): For AM/PM time to 24 Hours time and parseFromTwentyFourToAmPm(): For 24 Hours time to AM/PM time

A generic method for handling both start date and end date dropdown onSelect(): For setting startDate and endDate in the dropdown and tracking class properties

HTML

<h2>{{ title }}</h2>

<form [formGroup]="dateTrackForm">
  Start at:
  <select 
    formControlName="startDate"
    (change)="onSelect($event.target.value, 'startDate')" 
    id="skill">
    <option value="0" selected>Select</option>
    <option [value]="type" *ngFor="let type of startTimeArray; let i = index">
      {{type}}
    </option>
  </select>

  End at:
  <select 
    formControlName="endDate"
    (change)="onSelect($event.target.value, 'endDate')">
    <option value="0" selected>Select</option>
    <option [value]="type" *ngFor="let type of endTimeArray">
      {{type}}
    </option>
  </select>
</form>

TypeScript

export class AppComponent implements OnInit {
  public title = "Nested FormArray Example Add Form Fields Dynamically";
  public startTimeArray: string[] = [
    "7:00 AM", "8:00 AM", "9:00 AM", "10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM", "2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM", "7:00 PM", "8:00 PM",
  ];
  public endTimeArray: string[] = [
    "7:00 AM", "8:00 AM", "9:00 AM", "10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM", "2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM", "7:00 PM", "8:00 PM",
  ];
  public dates = {
    startDate: '08:00',
    endDate: '13:00',
  }

  // form name
  public dateTrackForm: FormGroup;

  // keeping track from startDate and endDate
  public startDate: string;
  public endDate: string;

  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    // response from some api, you obviously have to do some work
    let { startDate, endDate } = this.dates;
    this.dateTrackForm = this.fb.group({
      startDate: this.fb.control(''),
      endDate: this.fb.control('')
    });

    if (startDate) {
      this.startDate = startDate;
      this.dateTrackForm.get('startDate').patchValue(this.parseFromTwentyFourToAmPm(startDate));
    }
    if (endDate) {
      this.endDate = endDate;
      this.dateTrackForm.get('endDate').patchValue(this.parseFromTwentyFourToAmPm(endDate));
    }
  }

  // we will using same method for both the case and will identify start or end dates based on the second prameter for which I have defined an enum at the end of the file
  public onSelect(time: string, date: Dates): void {
    if (date === Dates.START_DATE) {
      this.startDate = this.parseFromAmPmToTwentyFour(time);
    } else if (date === Dates.END_DATE) {
      this.endDate = this.parseFromAmPmToTwentyFour(time);
    }

    // 24 hours time that you want already assigned to respective field and now you can simple do what you want with it.
  }

  // This method will parse the time from am/pm time to 24 hours time
  public parseFromAmPmToTwentyFour(time: string): string {
    let hours = Number(time.match(/^(\d+)/)[1]);
    const minutes = Number(time.match(/:(\d+)/)[1]);
    const AMPM = time.match(/\s(.*)$/)[1];
    if (AMPM == "PM" && hours < 12) hours = hours + 12;
    if (AMPM == "AM" && hours == 12) hours = hours - 12;
    let sHours = hours.toString();
    let sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;
    return `${sHours} : ${sMinutes}`;
  }

  // This method will parse the time from 24 hours time to am/pm time
  public parseFromTwentyFourToAmPm(time: string): string {
    const H = +time.substr(0, 2);
    const h = H % 12 || 12;
    const ampm = (H < 12 || H === 24) ? "AM" : "PM";
    time = h + time.substr(2, 3) + ' ' + ampm;
    return time;
  }
}

// enum for detecting start or end date
enum Dates {
  START_DATE = "startDate",
  END_DATE = "endDate",
}

Here's a StackBlitz that solves your issues now completely. https://stackblitz.com/edit/pm-am-time-conversion

Source for AM:PM to 24 Hours conversion: convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Source for 24 Hours to AM:PM conversion: Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

The existing solutions that I have used are the same and I have done some changes.

One thing I would like to mention is that you have just declared things and there was a lot of missing implemention like Reactive Form was just declared but wasn't used. In order to provide you with the solution I have to add the missing implementations too. Please before asking any such questions do try to add all the stuff you can.

Thanks to @Heretic Monkey for advising to updating the answer.

Immad Hamid
  • 789
  • 1
  • 8
  • 21
  • Please include relevant code here on Stack Overflow in addition to on any external site so that the answer is available even if the external link goes down or someone is prevented from accessing the external site. – Heretic Monkey Apr 10 '20 at 12:26
  • Btw it's a public link but in order to prevent any future issues, I'll update my answer in an hour or less. Thanks for letting me know @heretic and have a nice day – Immad Hamid Apr 10 '20 at 12:31
  • Thank you so mcuh for the answer, it helped me get values of start time and end time in my console. However I am not able to incorporate slice(index) function which was in my onSelect() function in my stackblitz code. – rawrstar Apr 10 '20 at 17:53
  • Let me check that in a while a while and I'll update you. You are welcome – Immad Hamid Apr 10 '20 at 18:08