From e3d3ad45e12d05a9012daada871c67c47f0eac17 Mon Sep 17 00:00:00 2001 From: t1m0n Date: Fri, 1 Mar 2024 00:24:48 +0300 Subject: [PATCH] #589 - added conversion from date-only string to local date --- src/utils.js | 15 +++++++++++++++ tests/options.test.js | 1 - tests/utils.test.js | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/utils.test.js diff --git a/src/utils.js b/src/utils.js index 39806cd3..4c7eb822 100644 --- a/src/utils.js +++ b/src/utils.js @@ -351,6 +351,15 @@ export function deepMerge(target, ...objects) { return target; } +/** + * Checks if ISO date string consists only of numbers + * @param {string} dateString + * @returns {boolean} + */ +function dateStringIsDateOnly(dateString) { + return /^\d{4}-\d{2}-\d{2}$/.test(dateString); +} + /** * Creates Date object from string or number. If passed param is instance of Date, then just returns it. * @param {number|string|Date} date @@ -360,6 +369,12 @@ export function createDate(date) { let resultDate = date; if (!(date instanceof Date)) { + // If string is date-only string, we should add time to it + // so created date will be in a local time + // https://github.com/t1m0n/air-datepicker/issues/589 + if (typeof date === 'string' && dateStringIsDateOnly(date)) { + date += 'T00:00:00'; + } resultDate = new Date(date); } diff --git a/tests/options.test.js b/tests/options.test.js index 8a473180..1197f4d3 100644 --- a/tests/options.test.js +++ b/tests/options.test.js @@ -1,6 +1,5 @@ import {beforeAll, afterEach, describe, test, it, expect} from '@jest/globals'; import Datepicker from 'datepicker'; -import {isSameDate} from 'utils'; import en from 'locale/en'; import de from 'locale/de'; import consts from 'consts'; diff --git a/tests/utils.test.js b/tests/utils.test.js new file mode 100644 index 00000000..968ebb7b --- /dev/null +++ b/tests/utils.test.js @@ -0,0 +1,34 @@ +import {createDate, getParsedDate} from '../src/utils'; +import {describe, it, expect} from '@jest/globals'; + + +describe('createDate', () => { + it('should return date object if it receives one', () => { + const date = new Date(); + const createdDate = createDate(date); + + expect(date).toEqual(createdDate); + }); + it('should create date from string', () => { + const dateString = '2024-03-01'; + const createdDate = createDate(dateString); + + expect(createdDate).toBeInstanceOf(Date); + + const {fullDate, fullMonth, year} = getParsedDate(createdDate); + const allEqual = year === 2024 && fullMonth === '03' && fullDate === '01'; + + expect(allEqual).toBeTruthy(); + }); + it('should create date from number', () => { + const time = 1709241680707; + const createdDate = createDate(time); + + expect(createdDate).toBeInstanceOf(Date); + + const {fullDate, fullMonth, year} = getParsedDate(createdDate); + const allEqual = year === 2024 && fullMonth === '03' && fullDate === '01'; + + expect(allEqual).toBeTruthy(); + }); +});