Skip to content

Instantly share code, notes, and snippets.

@paulirwin
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulirwin/cdd1624967f3f5564c18 to your computer and use it in GitHub Desktop.
Save paulirwin/cdd1624967f3f5564c18 to your computer and use it in GitHub Desktop.
BetterDate: a sane JavaScript Date API for handling just dates without UTC issues
class BetterDate {
private _date: Date;
constructor(unixTime: number) {
this._date = new Date(unixTime);
}
toDate(): Date {
return this._date;
}
valueOf(): number {
return this._date.getTime();
}
toString(): string {
return this._date.toISOString().substring(0, 10);
}
toAmericanString(): string {
return this.month + "/" + this.day + "/" + this.year;
}
get year(): number {
return this._date.getUTCFullYear();
}
get month(): number {
return this._date.getUTCMonth() + 1;
}
get day(): number {
return this._date.getUTCDate();
}
static parse(input: string): BetterDate {
var temp = new Date(Date.parse(input));
var iso = temp.toISOString().substring(0, 10) + "T00:00:00.000Z";
return new BetterDate(Date.parse(iso));
}
}
// usage:
// var x = BetterDate.parse("2014-01-20");
// var y = BetterDate.parse("Jan 21, 2014");
// x.toString();
// --> "2014-01-20"
// y.toString();
// --> "2014-01-21" // NOTE: try this with Date.parse in a non-UTC time zone!
// x < y
// --> true
// x.toAmericanString()
// --> "1/20/2014"
// x.year
// --> 2014
// x.month
// --> 1 // NOTE: this is 1-based like it should be!
// x.day
// --> 20 // NOTE: this is the day of the month, not the day of the week, like it should be!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment