@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
77 lines (76 loc) • 2.01 kB
JavaScript
import { LocalDate } from './localDate.js';
import { localTime } from './localTime.js';
/**
* Representation of a "time on the wall clock",
* which means "local time, regardless of timezone".
*
* Experimental simplified container object to hold
* date and time components as numbers.
* No math or manipulation is possible here.
* Can be pretty-printed as Date, Time or DateAndTime.
*/
export class WallTime {
year;
month;
day;
hour;
minute;
second;
constructor(obj) {
Object.assign(this, obj);
}
toLocalDate() {
return new LocalDate(this.year, this.month, this.day);
}
/**
* Example:
* WallTime is 1984-06-21 17:56:21
* .toLocalTime() will return a LocalTime Date instance
* holding that time in the local timezone.
*/
toLocalTime() {
return localTime.fromDateTimeObject(this);
}
toJSON() {
return this.toISODateTime();
}
toString() {
return this.toISODateTime();
}
/**
* Returns e.g: `1984-06-21 17:56:21`
* or (if seconds=false):
* `1984-06-21 17:56`
*/
toPretty(seconds = true) {
return this.toISODate() + ' ' + this.toISOTime(seconds);
}
/**
* Returns e.g: `1984-06-21T17:56:21`
*/
toISODateTime() {
return (this.toISODate() + 'T' + this.toISOTime());
}
/**
* Returns e.g: `1984-06-21`, only the date part of DateTime
*/
toISODate() {
return [
String(this.year).padStart(4, '0'),
String(this.month).padStart(2, '0'),
String(this.day).padStart(2, '0'),
].join('-');
}
/**
* Returns e.g: `17:03:15` (or `17:03` with seconds=false)
*/
toISOTime(seconds = true) {
return [
String(this.hour).padStart(2, '0'),
String(this.minute).padStart(2, '0'),
seconds && String(this.second).padStart(2, '0'),
]
.filter(Boolean)
.join(':');
}
}