forked from Yadro/time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTime.ts
More file actions
101 lines (85 loc) · 2.29 KB
/
DateTime.ts
File metadata and controls
101 lines (85 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { ITimeRangeModel } from '../modules/tasks/models/TaskModel';
import { format } from 'date-fns';
import { iterPrevCurrent } from './ArrayHelper';
function timePad(time: number): string {
return String(time).padStart(2, '0');
}
function onlySecs(sign: string, secs: number) {
return `${sign}${secs}s`;
}
function timeItemsToString(
sign: string,
hrs: number,
mins: number,
secs: number,
showSeconds: boolean
) {
if (hrs === 0 && mins === 0) {
return onlySecs(sign, secs);
}
let result = `${sign}${timePad(hrs)}:${timePad(mins)}`;
if (showSeconds) {
result += `:${timePad(secs)}`;
}
return result;
}
export function msToTime(s: number, showSeconds: boolean = true) {
if (!s) {
return '0s';
}
const sign = s < 0 ? '-' : '';
s = Math.abs(s);
const ms = s % 1000;
s = (s - ms) / 1000;
const secs = s % 60;
s = (s - secs) / 60;
const mins = s % 60;
const hrs = (s - mins) / 60;
return timeItemsToString(sign, hrs, mins, secs, showSeconds);
}
export function timeToMs(date: Date) {
const hours = date.getHours();
const minutes = date.getMinutes();
return (hours * 60 + minutes) * 60 * 1000;
}
export function calcDuration(taskTime: ITimeRangeModel[]): number {
return taskTime.reduce((prev, timeRange) => {
if (!timeRange.start) {
return 0;
}
if (!timeRange.end) {
return prev + new Date().getTime() - timeRange.start.getTime();
}
return prev + timeRange.end.getTime() - timeRange.start.getTime();
}, 0);
}
export function calcDurationGaps(taskTime: ITimeRangeModel[]): number {
let result = 0;
iterPrevCurrent(taskTime, (prev, cur) => {
if (prev?.end) {
result += cur.start.getTime() - prev.end.getTime();
}
});
const lastTask = taskTime[taskTime.length - 1];
if (lastTask && lastTask.end) {
result += new Date().getTime() - lastTask.end.getTime();
}
return result;
}
const TIME_FORMAT = 'HH:mm';
const NO_TIME = '--:--';
export function getTime(date: Date | undefined) {
if (!date) {
return NO_TIME;
}
return format(date, TIME_FORMAT);
}
export function estimateWorkingTimeEnd(
startDate: Date | undefined,
restTimeMs: number,
workingHoursMs: number
): Date | undefined {
return startDate
? new Date(startDate.getTime() + restTimeMs + workingHoursMs)
: undefined;
}