Commit ba7a0f2f authored by Olena Horal-Koretska's avatar Olena Horal-Koretska

Merge branch '220032-extract-date-utility-function' into 'master'

Extract differenceInMilliseconds datetime function

See merge request gitlab-org/gitlab!40708
parents 29981a1f cba1fc90
import { deprecatedCreateFlash as flash } from '~/flash';
import { s__, sprintf } from '~/locale';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
// Renders math using KaTeX in any element with the
// `js-render-math` class
......@@ -111,7 +112,7 @@ class SafeMathRenderer {
// Give the browser time to reflow the svg
waitForReflow(() => {
const deltaTime = Date.now() - this.startTime;
const deltaTime = differenceInMilliseconds(this.startTime);
this.totalMS += deltaTime;
this.renderElement();
......
......@@ -216,8 +216,9 @@ export const timeFor = (time, expiredLabel) => {
return timeago.format(time, `${timeagoLanguageCode}-remaining`).trim();
};
export const millisecondsPerDay = 1000 * 60 * 60 * 24;
export const getDayDifference = (a, b) => {
const millisecondsPerDay = 1000 * 60 * 60 * 24;
const date1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const date2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
......@@ -709,7 +710,7 @@ export const dateFromParams = (year, month, day) => {
* A utility function which computes the difference in seconds
* between 2 dates.
*
* @param {Date} startDate the start sate
* @param {Date} startDate the start date
* @param {Date} endDate the end date
*
* @return {Int} the difference in seconds
......@@ -717,3 +718,18 @@ export const dateFromParams = (year, month, day) => {
export const differenceInSeconds = (startDate, endDate) => {
return (endDate.getTime() - startDate.getTime()) / 1000;
};
/**
* A utility function which computes the difference in milliseconds
* between 2 dates.
*
* @param {Date|Int} startDate the start date. Can be either a date object or a unix timestamp.
* @param {Date|Int} endDate the end date. Can be either a date object or a unix timestamp. Defaults to now.
*
* @return {Int} the difference in milliseconds
*/
export const differenceInMilliseconds = (startDate, endDate = Date.now()) => {
const startDateInMS = startDate instanceof Date ? startDate.getTime() : startDate;
const endDateInMS = endDate instanceof Date ? endDate.getTime() : endDate;
return endDateInMS - startDateInMS;
};
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
export default (fn, { interval = 2000, timeout = 60000 } = {}) => {
const startTime = Date.now();
return new Promise((resolve, reject) => {
const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
const next = () => {
if (timeout === 0 || Date.now() - startTime < timeout) {
if (timeout === 0 || differenceInMilliseconds(startTime) < timeout) {
setTimeout(fn.bind(null, next, stop), interval);
} else {
reject(new Error('SIMPLE_POLL_TIMEOUT'));
......
......@@ -4,10 +4,13 @@ import { GlSparklineChart } from '@gitlab/ui/dist/charts';
import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue';
import { s__, sprintf } from '~/locale';
import { firstAndLastY } from '~/lib/utils/chart_utils';
import { formatDate } from '~/lib/utils/datetime_utility';
import {
formatDate,
differenceInMilliseconds,
millisecondsPerDay,
} from '~/lib/utils/datetime_utility';
import { formattedChangeInPercent } from '~/lib/utils/number_utils';
import ChartButtons from './vulnerability_chart_buttons.vue';
import { DAY_IN_MS } from '../store/modules/vulnerabilities/constants';
import { SEVERITY_LEVELS } from '../store/constants';
const ISO_DATE = 'isoDate';
......@@ -74,7 +77,7 @@ export default {
},
computed: {
startDate() {
return Date.now() - DAY_IN_MS * this.vulnerabilitiesHistoryDayRange;
return differenceInMilliseconds(millisecondsPerDay * this.vulnerabilitiesHistoryDayRange);
},
endDateCursor() {
return Date.now();
......
......@@ -9,10 +9,10 @@ import { s__, sprintf } from '~/locale';
import { firstAndLastY } from '~/lib/utils/chart_utils';
import { formattedChangeInPercent } from '~/lib/utils/number_utils';
import { differenceInMilliseconds, millisecondsPerDay } from '~/lib/utils/datetime_utility';
import ChartButtons from './vulnerability_chart_buttons.vue';
import { DAY_IN_MS, DAYS } from '../store/modules/vulnerabilities/constants';
import { DAYS } from '../store/modules/vulnerabilities/constants';
import { SEVERITY_LEVELS } from '../store/constants';
export default {
......@@ -74,7 +74,7 @@ export default {
});
},
startDate() {
return Date.now() - DAY_IN_MS * this.vulnerabilitiesHistoryDayRange;
return differenceInMilliseconds(millisecondsPerDay * this.vulnerabilitiesHistoryDayRange);
},
dateInfo() {
const formattedStartDate = dateFormat(this.startDate, 'mmmm dS');
......
......@@ -8,8 +8,6 @@ export const INFO = 'info';
export const UNKNOWN = 'unknown';
export const SEVERITIES = [CRITICAL, HIGH, MEDIUM, LOW, INFO, UNKNOWN];
export const DAY_IN_MS = 1000 * 60 * 60 * 24;
export const DAYS = {
THIRTY: 30,
SIXTY: 60,
......
import { shallowMount } from '@vue/test-utils';
import { GlPopover, GlLink, GlIcon } from '@gitlab/ui';
import GeoNodeLastUpdated from 'ee/geo_nodes/components/geo_node_last_updated.vue';
import {
HELP_NODE_HEALTH_URL,
GEO_TROUBLESHOOTING_URL,
STATUS_DELAY_THRESHOLD_MS,
} from 'ee/geo_nodes/constants';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('GeoNodeLastUpdated', () => {
let wrapper;
const staleStatusTime = new Date(Date.now() - STATUS_DELAY_THRESHOLD_MS).getTime();
const staleStatusTime = differenceInMilliseconds(STATUS_DELAY_THRESHOLD_MS);
const nonStaleStatusTime = new Date().getTime();
const defaultProps = {
......
import { shallowMount } from '@vue/test-utils';
import TimeAgo from 'ee/vue_shared/dashboards/components/time_ago.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('time ago component', () => {
let wrapper;
......@@ -7,7 +8,7 @@ describe('time ago component', () => {
beforeEach(() => {
wrapper = shallowMount(TimeAgo, {
propsData: {
time: new Date(Date.now() - 86400000).toISOString(),
time: new Date(differenceInMilliseconds(86400000)).toISOString(),
tooltipText: 'Finished',
},
});
......
import { TEST_HOST } from 'spec/test_constants';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
const AVATAR_URL = `${TEST_HOST}/dummy.jpg`;
......@@ -21,7 +22,7 @@ export const mockHeaders = {
export function mockPipelineData(
status = 'success',
id = 1,
finishedTimeStamp = new Date(Date.now() - 86400000).toISOString(),
finishedTimeStamp = new Date(differenceInMilliseconds(86400000)).toISOString(),
isTag = false,
) {
return {
......
......@@ -3,7 +3,7 @@ import { format } from 'timeago.js';
import EnvironmentItem from '~/environments/components/environment_item.vue';
import PinComponent from '~/environments/components/environment_pin.vue';
import DeleteComponent from '~/environments/components/environment_delete.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
import { environment, folder, tableData } from './mock_data';
describe('Environment item', () => {
......@@ -135,7 +135,7 @@ describe('Environment item', () => {
});
describe('in the past', () => {
const pastDate = new Date(Date.now() - 100000);
const pastDate = new Date(differenceInMilliseconds(100000));
beforeEach(() => {
factory({
propsData: {
......
......@@ -653,3 +653,17 @@ describe('differenceInSeconds', () => {
expect(datetimeUtility.differenceInSeconds(startDate, endDate)).toBe(expected);
});
});
describe('differenceInMilliseconds', () => {
const startDateTime = new Date('2019-07-17T00:00:00.000Z');
it.each`
startDate | endDate | expected
${startDateTime.getTime()} | ${new Date('2019-07-17T00:00:00.000Z')} | ${0}
${startDateTime} | ${new Date('2019-07-17T12:00:00.000Z').getTime()} | ${43200000}
${startDateTime} | ${new Date('2019-07-18T00:00:00.000Z').getTime()} | ${86400000}
${new Date('2019-07-18T00:00:00.000Z')} | ${startDateTime.getTime()} | ${-86400000}
`('returns $expected for $endDate - $startDate', ({ startDate, endDate, expected }) => {
expect(datetimeUtility.differenceInMilliseconds(startDate, endDate)).toBe(expected);
});
});
......@@ -5,6 +5,7 @@ import { Blob, BinaryBlob } from 'jest/blob/components/mock_data';
import waitForPromises from 'helpers/wait_for_promises';
import DeleteSnippetMutation from '~/snippets/mutations/deleteSnippet.mutation.graphql';
import SnippetHeader from '~/snippets/components/snippet_header.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('Snippet header component', () => {
let wrapper;
......@@ -67,7 +68,7 @@ describe('Snippet header component', () => {
name: 'Thor Odinson',
},
blobs: [Blob],
createdAt: new Date(Date.now() - 32 * 24 * 3600 * 1000).toISOString(),
createdAt: new Date(differenceInMilliseconds(32 * 24 * 3600 * 1000)).toISOString(),
};
mutationVariables = {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment