Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 

99 lignes
3.0 KiB

  1. import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
  2. import {FormBuilder, FormGroup} from "@angular/forms";
  3. @Component({
  4. selector: 'app-datetime-picker',
  5. templateUrl: './datetime-picker.component.html',
  6. styleUrl: './datetime-picker.component.scss'
  7. })
  8. export class DatetimePickerComponent implements OnInit {
  9. @Input() label: string = 'Date and Time';
  10. @Input() inputId: string = 'myId';
  11. @Input() initialValue: string | null = null;
  12. @Input() readonly: boolean = false;
  13. @Input() showSeconds: boolean = false;
  14. @Output() dateTimeChange = new EventEmitter<string | null>();
  15. form: FormGroup;
  16. constructor(private fb: FormBuilder) {
  17. this.form = this.fb.group({
  18. date: [''],
  19. time: ['']
  20. });
  21. }
  22. ngOnInit() {
  23. if (this.initialValue) {
  24. // Datum als UTC interpretieren
  25. const date = new Date(this.initialValue);
  26. this.form.patchValue({
  27. date: this.formatDate(date),
  28. time: this.formatTime(date)
  29. });
  30. }
  31. if (this.readonly) {
  32. this.form.disable();
  33. }
  34. this.form.valueChanges.subscribe(() => {
  35. if (!this.readonly) {
  36. this.emitDateTime();
  37. }
  38. });
  39. }
  40. private formatDate(date: Date): string {
  41. // ISO String verwenden und nur den Datumsteil extrahieren (YYYY-MM-DD)
  42. return date.toISOString().split('T')[0];
  43. }
  44. private formatTime(date: Date): string {
  45. // Zeit aus ISO String extrahieren
  46. const timeString = date.toISOString().split('T')[1];
  47. if (this.showSeconds) {
  48. // Rückgabe mit Sekunden (HH:MM:SS)
  49. return timeString.substring(0, 8);
  50. } else {
  51. // Nur Stunden und Minuten zurückgeben (HH:MM)
  52. return timeString.substring(0, 5);
  53. }
  54. }
  55. private emitDateTime() {
  56. const {date, time} = this.form.value;
  57. if (date && time) {
  58. const [year, month, day] = date.split('-');
  59. // Parse Zeit je nach Format (mit oder ohne Sekunden)
  60. let hours, minutes, seconds;
  61. if (this.showSeconds && time.split(':').length > 2) {
  62. [hours, minutes, seconds] = time.split(':');
  63. } else {
  64. [hours, minutes] = time.split(':');
  65. seconds = '00';
  66. }
  67. // Datum in UTC erstellen
  68. const dateTime = new Date(
  69. Date.UTC(
  70. Number(year),
  71. Number(month) - 1,
  72. Number(day),
  73. Number(hours),
  74. Number(minutes),
  75. Number(seconds || 0)
  76. )
  77. );
  78. // Als ISO-String formatieren, der automatisch in UTC ist
  79. const formattedDate = dateTime.toISOString();
  80. this.dateTimeChange.emit(formattedDate);
  81. } else {
  82. this.dateTimeChange.emit(null);
  83. }
  84. }
  85. }