Skip to content

Instantly share code, notes, and snippets.

@thlemercier
Created March 13, 2019 23:02
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 thlemercier/d130231018ca9179b7932da7bb743bf1 to your computer and use it in GitHub Desktop.
Save thlemercier/d130231018ca9179b7932da7bb743bf1 to your computer and use it in GitHub Desktop.
import { DateTime } from "luxon";
const DEFAULT_DATE = {
H24: { label: '24 Hours', hours: 24 },
D7: { label: '7 Days', hours: 24 * 7 },
D30: { label: '30 Days', hours: 24 * 30 }
}
/**
*
*/
export class DateDomain {
_formDate = null;
_apiDate = null;
_locale = null;
/**
*
* @param {date: Date, local: String} param0
*/
constructor ({date, locale = 'Australia/Sydney'}) {
this._formDate = date;
this._apiDate = DateTime.fromJSDate(date);
this._locale = locale;
}
static now (locale) {
return new DateDomain({ date: new Date(), locale: locale });
}
static newDate24HoursAgo (locale) {
return new DateDomain({ date: new Date(), locale: locale }).minus({ hours: 24 });
}
static newDate7DaysAgo (locale) {
return new DateDomain({ date: new Date(), locale: locale }).minus({ hours: 24 * 7 });
}
static newDate30DaysAgo (locale) {
return new DateDomain({ date: new Date(), locale: locale }).minus({ hours: 24 * 30 });
}
static fromTimestamp (timestampInSecond, locale = "Australia/Sydney") {
return new DateDomain({ date: new Date(timestampInSecond * 1000), locale: locale });
}
static fromISO (iso, locale = "Australia/Sydney") {
return new DateDomain({ date: new Date(iso), locale: locale });
}
get formDate () {
return this._formDate;
}
set formDate (formDate) {
this._formDate = formDate;
this._apiDate = DateTime.fromJSDate(formDate, { zone: this._locale });
}
get locale () {
return this._locale;
}
set locale (locale) {
this._locale = locale;
}
getApiFormatedDate () {
return this._apiDate.toString();
}
minus ({ hours }) {
this._apiDate = this._apiDate.minus({ hours: hours });
this._formDate = this._apiDate.toJSDate();
return this;
}
isAfter (date) {
return date.formDate - this.formDate;
}
isBefore (date) {
return this.formDate - date.formDate;
}
toFormat (format) {
return this._apiDate.toFormat(format);
}
toReadbleDate (granularity = 'DD at hh:mma') {
return this._apiDate.toLocaleString(DateTime.DATETIME_MED);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment