1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-11-30 08:26:59 +02:00
joplin/ReactNativeClient/lib/time-utils.js

115 lines
2.0 KiB
JavaScript
Raw Normal View History

const moment = require('moment');
2017-06-23 23:32:24 +02:00
class Time {
constructor() {
this.dateFormat_ = 'DD/MM/YYYY';
this.timeFormat_ = 'HH:mm';
this.locale_ = 'en-us';
}
locale() {
return this.locale_;
}
setLocale(v) {
moment.locale(v);
this.locale_ = v
}
dateFormat() {
return this.dateFormat_;
}
setDateFormat(v) {
this.dateFormat_ = v;
}
timeFormat() {
return this.timeFormat_;
}
setTimeFormat(v) {
this.timeFormat_ = v;
}
dateTimeFormat() {
return this.dateFormat() + ' ' + this.timeFormat();
}
2017-06-14 00:39:45 +02:00
unix() {
return Math.floor(Date.now() / 1000);
}
2017-06-19 00:06:10 +02:00
unixMs() {
return Date.now();
}
2017-06-19 00:06:10 +02:00
2017-09-10 18:56:27 +02:00
unixMsToObject(ms) {
return new Date(ms);
}
2017-09-10 18:56:27 +02:00
2017-06-19 00:06:10 +02:00
unixMsToS(ms) {
2017-06-19 21:18:22 +02:00
return Math.floor(ms / 1000);
}
2017-06-23 23:32:24 +02:00
unixMsToIso(ms) {
2019-07-29 15:43:53 +02:00
return (
moment
.unix(ms / 1000)
.utc()
.format('YYYY-MM-DDTHH:mm:ss.SSS') + 'Z'
);
}
2017-06-14 00:39:45 +02:00
2017-07-07 19:19:24 +02:00
unixMsToIsoSec(ms) {
2019-07-29 15:43:53 +02:00
return (
moment
.unix(ms / 1000)
.utc()
.format('YYYY-MM-DDTHH:mm:ss') + 'Z'
);
}
2017-07-07 19:19:24 +02:00
2017-07-12 22:39:47 +02:00
unixMsToLocalDateTime(ms) {
return moment.unix(ms / 1000).format('DD/MM/YYYY HH:mm');
}
2017-07-12 22:39:47 +02:00
formatMsToLocal(ms, format = null) {
if (format === null) format = this.dateTimeFormat();
2017-07-15 01:12:32 +02:00
return moment(ms).format(format);
}
formatLocalToMs(localDateTime, format = null) {
if (format === null) format = this.dateTimeFormat();
const m = moment(localDateTime, format);
if (m.isValid()) return m.toDate().getTime();
throw new Error('Invalid input for formatLocalToMs: ' + localDateTime);
}
// Mostly used as a utility function for the DateTime Electron component
anythingToDateTime(o, defaultValue = null) {
if (o && o.toDate) return o.toDate();
if (!o) return defaultValue;
let m = moment(o, time.dateTimeFormat());
if (m.isValid()) return m.toDate();
m = moment(o, time.dateFormat());
return m.isValid() ? m.toDate() : defaultValue;
}
2017-06-27 01:20:01 +02:00
msleep(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, ms);
});
}
2017-06-27 01:20:01 +02:00
sleep(seconds) {
return this.msleep(seconds * 1000);
}
2017-06-14 00:39:45 +02:00
}
const time = new Time();
2019-07-29 15:43:53 +02:00
module.exports = { time };