Created
May 1, 2018 00:04
-
-
Save piouc/7a3dcc4ffdcd0aeaf4e15fadffaef0e9 to your computer and use it in GitHub Desktop.
date-time.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateTime { | |
constructor(){ | |
this._year = null | |
this._month = null | |
this._date = null | |
this._hours = null | |
this._minutes = null | |
this._seconds = null | |
} | |
set year(year){ | |
year = Number(year) | |
this._year = Number.isNaN(year) ? null : Math.max(0, year) | |
} | |
get year(){ | |
return this._year | |
} | |
set month(month){ | |
month = Number(month) | |
this._month = Number.isNaN(month) ? null : inRange(0, 11, month) | |
} | |
get month(){ | |
return this._month | |
} | |
set date(date){ | |
date = Number(date) | |
this._date = Number.isNaN(date) ? null : inRange(1, 31, date) | |
} | |
get date(){ | |
return this._date | |
} | |
set hours(hours){ | |
hours = Number(hours) | |
this._hours = Number.isNaN(hours) ? null : inRange(0, 23, hours) | |
} | |
get hours(){ | |
return this._hours | |
} | |
set minutes(minutes){ | |
minutes = Number(minutes) | |
this._minutes = Number.isNaN(minutes) ? null : inRange(0, 59, minutes) | |
} | |
get minutes(){ | |
return this._minutes | |
} | |
set seconds(seconds){ | |
seconds = Number(seconds) | |
this._seconds = Number.isNaN(seconds) ? null : inRange(0, 59, seconds) | |
} | |
get seconds(){ | |
return this._seconds | |
} | |
toString(){ | |
return `${this.toDateString()} ${this.toTimeString()}` | |
} | |
toDateString(){ | |
const year = typeof this.year === 'number' ? this.year.toString().padStart(4, 0) : '----' | |
const month = typeof this.month === 'number' ? (this.month.toString() + 1).padStart(2, 0) : '--' | |
const date = typeof this.date === 'number' ? this.date.toString().padStart(2, 0) : '--' | |
return `${year} ${month} ${date}` | |
} | |
toTimeString(){ | |
const hours = typeof this.hours === 'number' ? this.hours.toString().padStart(2, 0) : '--' | |
const minutes = typeof this.minutes === 'number' ? this.minutes.toString().padStart(2, 0) : '--' | |
return `${hours}:${minutes}` | |
} | |
toDate(){ | |
return new Date(this.year, this.month, this.date, this.minutes, this.seconds) | |
} | |
} | |
function inRange(min, max, value){ | |
return Math.max(min, Math.min(max, value)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment