mirror of
https://github.com/ionic-team/ionic-framework.git
synced 2025-08-23 22:17:40 +08:00
fix(datetime): date strings no longer revert to previous day (#18018)
fixes #17977
This commit is contained in:
@ -248,8 +248,20 @@ export function parseDate(val: string | undefined | null): DatetimeData | undefi
|
||||
* such as "01:47"
|
||||
*/
|
||||
export const getLocalDateTime = (dateString: any = ''): Date => {
|
||||
const date = (typeof dateString === 'string' && dateString.length > 0) ? new Date(dateString) : new Date();
|
||||
/**
|
||||
* Ensures that YYYY-MM-DD, YYYY-MM,
|
||||
* YYYY-DD, etc does not get affected
|
||||
* by timezones and stays on the day/month
|
||||
* that the user provided
|
||||
*/
|
||||
if (
|
||||
dateString.length === 10 ||
|
||||
dateString.length === 7
|
||||
) {
|
||||
dateString += ' ';
|
||||
}
|
||||
|
||||
const date = (typeof dateString === 'string' && dateString.length > 0) ? new Date(dateString) : new Date();
|
||||
return new Date(
|
||||
Date.UTC(
|
||||
date.getFullYear(),
|
||||
@ -267,7 +279,6 @@ export function updateDate(existingData: DatetimeData, newData: any): boolean {
|
||||
|
||||
if (!newData || typeof newData === 'string') {
|
||||
const localDateTime = getLocalDateTime(newData);
|
||||
|
||||
if (!Number.isNaN(localDateTime.getTime())) {
|
||||
newData = localDateTime.toISOString();
|
||||
}
|
||||
|
@ -52,6 +52,23 @@ describe('Datetime', () => {
|
||||
expect(convertToLocal.toISOString()).toEqual(expectedDateString);
|
||||
});
|
||||
});
|
||||
|
||||
it('should format a date string and not get affected by the timezone offset', () => {
|
||||
|
||||
const dateStringTests = [
|
||||
{ input: '2019-03-20', expectedOutput: '2019-03-20' },
|
||||
{ input: '1994-04-15', expectedOutput: '1994-04-15' },
|
||||
{ input: '2008-09-02', expectedOutput: '2008-09-02' },
|
||||
{ input: '1995-02', expectedOutput: '1995-02' },
|
||||
{ input: '1994-03-14', expectedOutput: '1994-03-14' },
|
||||
{ input: '9 01:47', expectedOutput: '09-01T01:47' }
|
||||
];
|
||||
|
||||
dateStringTests.forEach(test => {
|
||||
const convertToLocal = getLocalDateTime(test.input);
|
||||
expect(convertToLocal.toISOString()).toContain(test.expectedOutput);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('daysInMonth()', () => {
|
||||
|
Reference in New Issue
Block a user