Skip to content

Instantly share code, notes, and snippets.

@mlienau
Last active April 26, 2023 18:58
Show Gist options
  • Save mlienau/38dc3daad770ae7e82d7b4c67d602a00 to your computer and use it in GitHub Desktop.
Save mlienau/38dc3daad770ae7e82d7b4c67d602a00 to your computer and use it in GitHub Desktop.
An Angular directive to update a input type date's year to the current year if you only type the last two digits of the current year

HTML <input type="date" /> elements store the value as an ISO8601 (YYYY-MM-DD) date string, but for us Americans it's very common for us to write the date as m/d/yy.

The Problem

If you write the value as M/D/YY, that's a valid date but the value becomes 00YY-MM-DD which is an invalid SQL Server date and causes errors when it shouldn't necessarilly.

Adding this directive to any <input type="date" /> should change the value to {CURRENT_FULL_YEAR}-MM-DD automatically if you enter M/D/{LAST_TWO_DIGITS_OF_CURRENT_YEAR}.

Disclaimer - This probably will not work well after the year 9999.

import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: "input[type=date][appTwoDigitYearFixer]",
})
export class TwoDigitYearFixerDirective {
constructor(private control: NgControl) {
if (!control) {
throw new Error("The TwoDigitYearFixerDirective must be used with a formControl");
}
}
@HostListener("input", ["$event"])
public onClick(e: Event): void {
const currentYear = new Date().getFullYear().toString();
const currentYearAs2Digits = currentYear.substring(2, 4);
const inputValue = (e.target as HTMLInputElement).value;
const matcher = `00${currentYearAs2Digits}`;
if (inputValue && inputValue.startsWith(matcher)) {
const newValue = inputValue.replace(matcher, currentYear);
this.control.control.setValue(newValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment