What is the most effective way to split time into two separate parts?

Suppose a user enters the time as 12:34 and we need to split it into two different parts to save it in an array like [12, 34]. How can this be achieved using Angular?

I attempted to split them but my solutions were unsuccessful! I am currently utilizing <ngx-timepicker-field> in Angular and here is my HTML markup:

<ngx-timepicker-field 
     timepickerClass="custom-timepicker-css"
     [defaultTime]="'00:00'"
     [formControlName]="'start_time'"
     [format]="24"
     [clockTheme]="theme"
></ngx-timepicker-field>

Answer №1

To separate a string value and assign it to a new variable, you can utilize the split function with the following code snippet.

const startValue: string = this.formData.get('start').value;
const splitValues: string[] = startValue.split('-');

By executing the above code, you will have ['abc', '123'] stored in splitValues.

Note: * In this example, this.formData references your FormData object.

Answer №2

Implementing a getter method can help you access the split value easily!

get splitDate() {
    const value = this.formControlItem && this.formControlItem.value;
    if (value.includes('AM') || value.includes('PM')) {
      const split = value && value.split(':');
      const amPm =
        (split && split[1] && split[1].substr(-2, split[1].length)) || 'AM';
      return value
        ? [split[0], split[1].substr(0, split[1].length - 2), amPm]
        : [];
    } else {
      return (value && value.split(':')) || [];
    }
  }

  get splitDateWithPadding() {
    const value = this.formControlItem && this.formControlItem.value;
    if (value.includes('AM') || value.includes('PM')) {
      const split = value && value.split(':');
      const amPm =
        (split && split[1] && split[1].substr(-2, split[1].length)) || 'AM';
      const firstPadded = split[0] && split[0].padStart(2, '0');
      const split1 = split[1].substr(0, split[1].length - 2);
      const secondPadded = split1 && split1.padStart(2, '0');
      return value ? [firstPadded, secondPadded, amPm] : [];
    } else {
      return (value && value.split(':')) || [];
    }
  }

html

<mat-form-field appearance="outline">
  <mat-label>MY FIELD</mat-label>
  <input
    type="text"
    matInput
    [ngxMatTimepicker]="timepicker"
    [format]="12"
    [required]="required"
    readonly
    [formControl]="formControlItem"
  />

  <mat-icon
    matPrefix
    *ngIf="formControlItem.value && !formControlItem.disabled && !required"
    (click)="onClear($event)"
  >
    close
  </mat-icon>

  <mat-icon
    matSuffix
    *ngIf="!formControlItem.disabled"
    (click)="openFromIcon(timepicker)"
    >schedule</mat-icon
  >
</mat-form-field>

<ngx-mat-timepicker
  #timepicker
  [enableKeyboardInput]="true"
  [max]="maxTime"
  [min]="minTime"
></ngx-mat-timepicker>
<br />
{{ formControlItem.value | json }}
<br />
<br />
{{ splitDate | json }}

<br />
<br />
{{ splitDateWithPadding | json }}

Check out the updated code on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

KeysOfType: Identifying the precise data type of each property

I came across a solution called KeysOfType on a post at : type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T]; Here are the interfaces being used: interface SomeInterface { a: number; b: string; } interface A ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

Specify the data type of a nested object in a React component with TypeScript

Interface Button{ buttonTitle: { name?: string; } } What is the best way to specify a type for the buttonTitle property? ...

Creating an Observable from static data in Angular that resembles an HTTP request

I have a service with the following method: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observable<string> { i ...

Converting an integer into a String Enum in TypeScript can result in an undefined value being returned

Issue with Mapping Integer to Enum in TypeScript export enum MyEnum { Unknown = 'Unknown', SomeValue = 'SomeValue', SomeOtherValue = 'SomeOtherValue', } Recently, I encountered a problem with mapping integer val ...

Retrieve the final variable in an Observable sequence

In my code, I have a variable called 'messages' which stores messages from a conversation: messages: Observable<Message[]>; To populate the 'messages' variable, I do the following: const newMessage = new Message(objMessage); ne ...

The compilation of @types/socket.io-redis fails because it cannot locate the Adapter exported by @types/socket.io, which is necessary for its functionality

It seems like there may be an issue with my tsconfig file or something similar. npm run compile > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c69626b6562694c3d223c">[email protected]</a> compile /User ...

Contrasting importing a module in app.module versus a component

Angular 5 Can you explain the distinction between importing a module in app.module versus importing it directly into the component where it is needed? In particular, why is it necessary for a module to be included in node modules, app.module, the import ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

A guide on utilizing the TypeScript compilerOptions --outDir feature

Recently, I encountered an error message from the compiler stating: Cannot write file 'path/file.json' because it would overwrite input file. After some investigation, most of the solutions suggested using outDir to resolve this issue. Although t ...

Angular 10 introduces a new feature where BehaviorSubject can now hold and emit two

Currently, I am attempting to log in using Firebase. The login system is functioning correctly; however, I am facing a challenge in retrieving the error name from the authentication service and displaying it in my login component. SignIn(email: string, pas ...

Ever since incorporating bootstrap, the functionality of *ngFor has been disrupted and now nothing seems to be working as

There seems to be an issue with the property binding ngForOf in this embedded template. It is not being used by any directive. Please make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations" <d ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Combining divs with identical values in Angular

I am working on creating my very own custom Calendar. Take a look at the full example of my component here I need help figuring out how to combine week divs that share the same value {{day.weekNumber}} so that there is only one div for each shared value, ...

The parameters 'event' and 'payload' do not match in type

Upon running the build command, I encountered a type error that states: Type error: Type '(event: React.FormEvent) => void' is not assignable to type 'FormSubmitHandler'. Types of parameters 'event' and 'payload&apos ...

How come the Angular8 form status registers as VALID even if the input fields are empty?

The following is the structure of the component: export class SchedulerComponent implements OnInit { schedulerForm : FormGroup; constructor(private fb: FormBuilder, private schedulerReportService: SchedulerReportService) { this. ...

Tips for sending FormData and request body with angular's httpclient

I need help updating my Angular application package from @angular/http to @angular/common/http. During the process, my code is breaking for a specific reason. Previously, I was able to send both form data and request body in the following manner: this.ht ...