Repository navigation
Expand file tree
/
Copy pathDateUtil.ts
More file actions
108 lines (91 loc) · 2.79 KB
/
Copy pathDateUtil.ts
File metadata and controls
108 lines (91 loc) · 2.79 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
102
103
104
105
106
107
108
export namespace DateUtil
{
export function to_string(date: Date, hms: boolean = false): string
{
let ret: string = `${date.getFullYear()}-${_To_cipher_string(date.getMonth()+1)}-${_To_cipher_string(date.getDate())}`;
if (hms === true)
ret += ` ${_To_cipher_string(date.getHours())}:${_To_cipher_string(date.getMinutes())}:${_To_cipher_string(date.getSeconds())}`;
return ret;
}
export interface IDifference
{
year: number;
month: number;
date: number;
}
export function diff(x: Date | string, y: Date | string): IDifference
{
x = _To_date(x);
y = _To_date(y);
// FIRST DIFFERENCES
let ret: IDifference =
{
year: x.getFullYear() - y.getFullYear(),
month: x.getMonth() - y.getMonth(),
date: x.getDate() - y.getDate()
};
//----
// HANDLE NEGATIVE ELEMENTS
//----
// DATE
if (ret.date < 0)
{
let last: number = last_date(y.getFullYear(), y.getMonth());
--ret.month;
ret.date = x.getDate() + (last - y.getDate());
}
// MONTH
if (ret.month < 0)
{
--ret.year;
ret.month = 12 + ret.month;
}
return ret;
}
export function last_date(year: number, month: number): number
{
// LEAP MONTH
if (month == 1 && year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0))
return 29;
else
return LAST_DATES[month];
}
export function add_years(date: Date, value: number): Date
{
date = new Date(date);
date.setFullYear(date.getFullYear() + value);
return date;
}
export function add_months(date: Date, value: number): Date
{
date = new Date(date);
let newYear: number = date.getFullYear() + Math.floor((date.getMonth() + value) / 12);
let newMonth: number = (date.getMonth() + value) % 12;
let lastDate: number = last_date(newYear, newMonth - 1);
if (lastDate < date.getDate())
date.setDate(lastDate);
date.setMonth(value - 1);
return date;
}
export function add_days(date: Date, value: number): Date
{
date = new Date();
date.setDate(date.getDate() + value);
return date;
}
function _To_date(date: string | Date): Date
{
if (date instanceof Date)
return date;
else
return new Date(date);
}
function _To_cipher_string(val: number): string
{
if (val < 10)
return "0" + val;
else
return String(val);
}
const LAST_DATES: number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
}