UNPKG

1.78 kBJavaScriptView Raw
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15'use strict';
16
17const dayjs = require('dayjs');
18const utc = require('dayjs/plugin/utc');
19dayjs.extend(utc);
20const quarterOfYear = require('dayjs/plugin/quarterOfYear');
21dayjs.extend(quarterOfYear);
22const minMax = require('dayjs/plugin/minMax');
23dayjs.extend(minMax);
24const duration = require('dayjs/plugin/duration');
25dayjs.extend(duration);
26
27/**
28 * Ensures there is a proper current time
29 *
30 * @param {string} [currentTime] - the definition of 'now'
31 * @param {number} [utcOffset] - UTC Offset for this execution
32 * @returns {object} if valid, the dayjs object for the current time
33 */
34function setCurrentTime(currentTime, utcOffset) {
35 // Default UTC offset to local time
36 const utcOffsetResolved = typeof utcOffset === 'number' ? utcOffset : dayjs().utcOffset();
37 const currentTimeUTC = currentTime ? dayjs.utc(currentTime) : dayjs().utc();
38 const currentTimeResolved = currentTimeUTC.utcOffset(utcOffsetResolved);
39 if (!currentTimeResolved.isValid()) {
40 throw new Error(`Cannot set current time to '${currentTime}' with UTC offset '${utcOffset}'`);
41 }
42 return {
43 currentTime: currentTimeResolved,
44 utcOffset: utcOffsetResolved
45 };
46}
47
48module.exports = { setCurrentTime };