1 import { Component, Input, OnInit } from '@angular/core';
2 import { UntypedFormControl } from '@angular/forms';
4 import { NgbCalendar, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
5 import moment from 'moment';
6 import { Subscription } from 'rxjs';
9 selector: 'cd-date-time-picker',
10 templateUrl: './date-time-picker.component.html',
11 styleUrls: ['./date-time-picker.component.scss']
13 export class DateTimePickerComponent implements OnInit {
15 control: UntypedFormControl;
33 minDate: NgbDateStruct;
39 date: { [key: number]: string }[] = [];
45 constructor(private calendar: NgbCalendar) {}
48 this.minDate = this.calendar.getToday();
50 this.format = 'YYYY-MM-DD';
51 } else if (this.hasSeconds) {
52 this.format = 'YYYY-MM-DD HH:mm:ss';
54 this.format = 'YYYY-MM-DD HH:mm';
57 let mom = moment(this.control?.value, this.format);
59 if (!mom.isValid() || mom.isBefore(moment())) {
63 this.date.push(mom.format('YYYY-MM-DD'));
64 const time = mom.format('HH:mm:ss');
65 this.time = mom.format('hh:mm');
66 this.ampm = mom.hour() >= 12 ? 'PM' : 'AM';
77 onModelChange(event?: any) {
79 if (Array.isArray(event)) {
80 this.datetime.date = moment(event[0]).format('YYYY-MM-DD');
81 } else if (event && ['AM', 'PM'].includes(event)) {
82 const initialMoment = moment(this.datetime.time, 'hh:mm:ss A');
83 const updatedMoment = initialMoment.set(
85 (initialMoment.hour() % 12) + (event === 'PM' ? 12 : 0)
87 this.datetime.time = moment(updatedMoment).format('HH:mm:ss');
88 this.datetime.ampm = event;
91 this.datetime.time = moment(`${this.datetime.date} ${time} ${this.datetime.ampm}`).format(
97 const datetime = moment(`${this.datetime.date} ${this.datetime.time}`).format(this.format);
100 this.control.setValue(datetime);
104 this.control.setValue('');