• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

typeorm / typeorm / 14796576772

02 May 2025 01:52PM UTC coverage: 45.367% (-30.9%) from 76.309%
14796576772

Pull #11434

github

web-flow
Merge ec4ce2d00 into fadad1a74
Pull Request #11434: feat: release PR releases using pkg.pr.new

5216 of 12761 branches covered (40.87%)

Branch coverage included in aggregate %.

11439 of 23951 relevant lines covered (47.76%)

15712.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

63.89
/src/util/DateUtils.ts
1
import { ColumnMetadata } from "../metadata/ColumnMetadata"
2
import dayjs from "dayjs"
4✔
3

4
/**
5
 * Provides utilities to transform hydrated and persisted data.
6
 */
7
export class DateUtils {
4✔
8
    // -------------------------------------------------------------------------
9
    // Public Static Methods
10
    // -------------------------------------------------------------------------
11

12
    /**
13
     * Normalizes date object hydrated from the database.
14
     */
15
    static normalizeHydratedDate(
16
        mixedDate: Date | string | undefined,
17
    ): Date | string | undefined {
18
        if (!mixedDate) return mixedDate
1,839!
19

20
        return typeof mixedDate === "string"
1,839✔
21
            ? new Date(mixedDate)
22
            : (mixedDate as Date)
23
    }
24

25
    /**
26
     * Converts given value into date string in a "YYYY-MM-DD" format.
27
     */
28
    static mixedDateToDateString(value: string | Date): string {
29
        if (value instanceof Date) {
31✔
30
            return (
11✔
31
                this.formatZerolessValue(value.getFullYear(), 4) +
32
                "-" +
33
                this.formatZerolessValue(value.getMonth() + 1) +
34
                "-" +
35
                this.formatZerolessValue(value.getDate())
36
            )
37
        }
38

39
        return value
20✔
40
    }
41

42
    /**
43
     * Converts given value into date object.
44
     */
45
    static mixedDateToDate(
46
        mixedDate: Date | string,
47
        toUtc: boolean = false,
29✔
48
        useMilliseconds = true,
29✔
49
    ): Date {
50
        /**
51
         * new Date(ISOString) is not a reliable parser to date strings.
52
         * It's better to use 'date-fns' parser to parser string in ISO Format.
53
         *
54
         * The problem here is with wrong timezone.
55
         *
56
         * For example:
57
         *
58
         * ``new Date('2021-04-28')`` will generate `2021-04-28T00:00:00.000Z`
59
         * in my timezone, which is not true for my timezone (GMT-0300). It should
60
         * be `2021-04-28T03:00:00.000Z` as `new Date(2021, 3, 28)` generates.
61
         *
62
         * https://stackoverflow.com/a/2587398
63
         */
64
        let date =
65
            typeof mixedDate === "string"
29✔
66
                ? dayjs(mixedDate).toDate()
67
                : mixedDate
68

69
        if (toUtc)
29!
70
            date = new Date(
×
71
                date.getUTCFullYear(),
72
                date.getUTCMonth(),
73
                date.getUTCDate(),
74
                date.getUTCHours(),
75
                date.getUTCMinutes(),
76
                date.getUTCSeconds(),
77
                date.getUTCMilliseconds(),
78
            )
79

80
        if (!useMilliseconds) date.setUTCMilliseconds(0)
29!
81

82
        return date
29✔
83
    }
84

85
    /**
86
     * Converts given value into time string in a "HH:mm:ss" format.
87
     */
88
    static mixedDateToTimeString(
89
        value: Date | any,
90
        skipSeconds: boolean = false,
4✔
91
    ): string | any {
92
        if (value instanceof Date)
4✔
93
            return (
4✔
94
                this.formatZerolessValue(value.getHours()) +
95
                ":" +
96
                this.formatZerolessValue(value.getMinutes()) +
97
                (!skipSeconds
4!
98
                    ? ":" + this.formatZerolessValue(value.getSeconds())
99
                    : "")
100
            )
101

102
        return value
×
103
    }
104

105
    /**
106
     * Converts given value into time string in a "HH:mm:ss" format.
107
     */
108
    static mixedTimeToDate(value: Date | any): string | any {
109
        if (typeof value === "string") {
×
110
            const [hours, minutes, seconds] = value.split(":")
×
111
            const date = new Date()
×
112
            if (hours) date.setHours(parseInt(hours))
×
113
            if (minutes) date.setMinutes(parseInt(minutes))
×
114
            if (seconds) date.setSeconds(parseInt(seconds))
×
115
            return date
×
116
        }
117

118
        return value
×
119
    }
120

121
    /**
122
     * Converts given string value with "-" separator into a "HH:mm:ss" format.
123
     */
124
    static mixedTimeToString(
125
        value: string | any,
126
        skipSeconds: boolean = false,
6✔
127
    ): string | any {
128
        value =
6✔
129
            value instanceof Date
6!
130
                ? value.getHours() +
131
                  ":" +
132
                  value.getMinutes() +
133
                  (!skipSeconds ? ":" + value.getSeconds() : "")
×
134
                : value
135
        if (typeof value === "string") {
6✔
136
            return value
6✔
137
                .split(":")
138
                .map((v) => (v.length === 1 ? "0" + v : v)) // append zero at beginning if we have a first-zero-less number
18!
139
                .join(":")
140
        }
141

142
        return value
×
143
    }
144

145
    /**
146
     * Converts given value into datetime string in a "YYYY-MM-DD HH-mm-ss" format.
147
     */
148
    static mixedDateToDatetimeString(
149
        value: Date | any,
150
        useMilliseconds?: boolean,
151
    ): string | any {
152
        if (typeof value === "string") {
×
153
            value = new Date(value)
×
154
        }
155
        if (value instanceof Date) {
×
156
            let finalValue =
157
                this.formatZerolessValue(value.getFullYear(), 4) +
×
158
                "-" +
159
                this.formatZerolessValue(value.getMonth() + 1) +
160
                "-" +
161
                this.formatZerolessValue(value.getDate()) +
162
                " " +
163
                this.formatZerolessValue(value.getHours()) +
164
                ":" +
165
                this.formatZerolessValue(value.getMinutes()) +
166
                ":" +
167
                this.formatZerolessValue(value.getSeconds())
168

169
            if (useMilliseconds)
×
170
                finalValue += `.${this.formatMilliseconds(
×
171
                    value.getMilliseconds(),
172
                )}`
173

174
            value = finalValue
×
175
        }
176

177
        return value
×
178
    }
179

180
    /**
181
     * Converts given value into utc datetime string in a "YYYY-MM-DD HH-mm-ss.sss" format.
182
     */
183
    static mixedDateToUtcDatetimeString(value: Date | any): string | any {
184
        if (typeof value === "string") {
339✔
185
            value = new Date(value)
6✔
186
        }
187
        if (value instanceof Date) {
339✔
188
            return (
339✔
189
                this.formatZerolessValue(value.getUTCFullYear(), 4) +
190
                "-" +
191
                this.formatZerolessValue(value.getUTCMonth() + 1) +
192
                "-" +
193
                this.formatZerolessValue(value.getUTCDate()) +
194
                " " +
195
                this.formatZerolessValue(value.getUTCHours()) +
196
                ":" +
197
                this.formatZerolessValue(value.getUTCMinutes()) +
198
                ":" +
199
                this.formatZerolessValue(value.getUTCSeconds()) +
200
                "." +
201
                this.formatMilliseconds(value.getUTCMilliseconds())
202
            )
203
        }
204

205
        return value
×
206
    }
207

208
    /**
209
     * Converts each item in the given array to string joined by "," separator.
210
     */
211
    static simpleArrayToString(value: any[] | any): string[] | any {
212
        if (Array.isArray(value)) {
3✔
213
            return (value as any[]).map((i) => String(i)).join(",")
9✔
214
        }
215

216
        return value
×
217
    }
218

219
    /**
220
     * Converts given string to simple array split by "," separator.
221
     */
222
    static stringToSimpleArray(value: string | any): string | any {
223
        if (typeof value === "string") {
3✔
224
            if (value.length > 0) {
3!
225
                return value.split(",")
3✔
226
            } else {
227
                return []
×
228
            }
229
        }
230

231
        return value
×
232
    }
233

234
    static simpleJsonToString(value: any): string {
235
        return JSON.stringify(value)
22✔
236
    }
237

238
    static stringToSimpleJson(value: any) {
239
        return typeof value === "string" ? JSON.parse(value) : value
25✔
240
    }
241

242
    static simpleEnumToString(value: any) {
243
        return "" + value
22✔
244
    }
245

246
    static stringToSimpleEnum(value: any, columnMetadata: ColumnMetadata) {
247
        if (
80✔
248
            columnMetadata.enum &&
202✔
249
            !isNaN(value) &&
250
            columnMetadata.enum.indexOf(parseInt(value)) >= 0
251
        ) {
252
            // convert to number if that exists in poosible enum options
253
            value = parseInt(value)
30✔
254
        }
255

256
        return value
80✔
257
    }
258

259
    // -------------------------------------------------------------------------
260
    // Private Static Methods
261
    // -------------------------------------------------------------------------
262

263
    /**
264
     * Formats given number to "0x" format, e.g. if the totalLength = 2 and the value is 1 then it will return "01".
265
     */
266
    private static formatZerolessValue(value: number, totalLength = 2): string {
1,729✔
267
        const pad = "0".repeat(totalLength)
2,079✔
268

269
        return String(`${pad}${value}`).slice(-totalLength)
2,079✔
270
    }
271

272
    /**
273
     * Formats given number to "0x" format, e.g. if it is 1 then it will return "01".
274
     */
275
    private static formatMilliseconds(value: number): string {
276
        if (value < 10) {
339✔
277
            return "00" + value
230✔
278
        } else if (value < 100) {
109✔
279
            return "0" + value
12✔
280
        } else {
281
            return String(value)
97✔
282
        }
283
    }
284
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc