Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save necojackarc/62e35d927bda809816ee8c574cf16341 to your computer and use it in GitHub Desktop.
Save necojackarc/62e35d927bda809816ee8c574cf16341 to your computer and use it in GitHub Desktop.
JavaScript DateOnly and TimeOnly classes
'use strict';

const moment = require('moment');

class DateOnly {
  /**
   * @param {moment|Date|string} input an object or a string moment.js can parse
   */
  constructor(input) {
    if (typeof(input) === 'string') {
      // Raise an error if the given string has redundant time information
      this.datetime = moment(`${input}T00:00:00.000`);
    } else {
      this.datetime = moment(input);
    }

    if (!this.datetime.isValid()) {
      throw new Error('invalid date format is given');
    }
  }

  toISOString(...args) {
    return this.datetime.toISOString(...args).split('T')[0];
  }

  format(string) {
    if (!string) {
      return this.datetime.format().split('T')[0];
    }

    return this.datetime.format(string);
  }
}

class TimeOnly {
  /**
   * @param {moment|Date|string} input an object or a string moment.js can parse
   */
  constructor(input) {
    if (typeof(input) === 'string') {
      // add '1970-01-01T' to parse it as a valid datetime string
      // '1970-01-01T' doesn't matter; it's never used after parse
      this.datetime = moment(`1970-01-01T${input}`);
    } else {
      this.datetime = moment(input);
    }

    if (!this.datetime.isValid()) {
      throw new Error('invalid time format is given');
    }
  }

  toISOString(...args) {
    return this.datetime.toISOString(...args).split('T')[1];
  }

  format(string) {
    if (!string) {
      return this.datetime.format().split('T')[1];
    }

    return this.datetime.format(string);
  }
}

module.exports = {
  DateOnly,
  TimeOnly,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment