0

I have a DateInfo class and I have a method (toString) that returns the appropriate date format. What to use to not write my own method (toString) just use the built-in Date object? I have a DateInfo class and I have a method (toString) that returns the appropriate date format. What to use to not write my own method (toString) just use the built-in Date object and get the same effect??

Class DateInfo{
 day= 3,
  hour=18,
  minute= 22,
  month= 11,
  second=54,
  timeZoneOffset= -60,
  year= 2022

  private isInteger(value: any): value is number {
    return (
      typeof value === 'number' &&
      isFinite(value) &&
      Math.floor(value) === value
    );
  }

  public toString(): string {
    if (
      this.isInteger(this.year) &&
      this.isInteger(this.month) &&
      this.isInteger(this.day)
    ) {
      const year = this.year.toString().padStart(2, '0');
      const month = this.month.toString().padStart(2, '0');
      const day = this.day.toString().padStart(2, '0');

      if (!this.hour) {
        this.hour = 0;
      }
      if (!this.minute) {
        this.minute = 0;
      }
      if (!this.second) {
        this.second = 0;
      }
      if (!this.timeZoneOffset) {
        this.timeZoneOffset = new Date().getTimezoneOffset();
      }

      const hour = this.hour.toString().padStart(2, '0');
      const minute = this.minute.toString().padStart(2, '0');
      const second = this.second.toString().padStart(2, '0');

      const tzo = -this.timeZoneOffset;
      const dif = tzo >= 0 ? '+' : '-',
        pad = function (num) {
          const norm = Math.floor(Math.abs(num));
          return (norm < 10 ? '0' : '') + norm;
        };

      const isoString = `${pad(year)}-${pad(month)}-${pad(day)}T${pad(
        hour
      )}:${pad(minute)}:${pad(second)}${dif}${pad(tzo / 60)}:${pad(tzo % 60)}`;

      return isoString;
    }

    return null;
  }
}
rdsm2
  • 9
  • 5
  • There are a huge number of questions and answers about [formatting *Dates*](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date), surely one of those has your answer? E.g. [*How to ISO 8601 format a Date with Timezone Offset in JavaScript?*](https://stackoverflow.com/questions/17415579/how-to-iso-8601-format-a-date-with-timezone-offset-in-javascript) – RobG Nov 23 '22 at 20:55

0 Answers0