Skip to content

Commit

Permalink
#589 - added conversion from date-only string to local date
Browse files Browse the repository at this point in the history
  • Loading branch information
t1m0n committed Feb 29, 2024
1 parent 18c975a commit e3d3ad4
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}

Expand Down
1 change: 0 additions & 1 deletion tests/options.test.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
34 changes: 34 additions & 0 deletions tests/utils.test.js
Original file line number Diff line number Diff line change
@@ -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();
});
});

0 comments on commit e3d3ad4

Please # to comment.