Skip to content

Commit 1db5098

Browse files
Andrea Barbassoalisaismailati
authored andcommitted
Merged in task/dspace-cris-2023_02_x/DSC-1833 (pull request DSpace#2326)
[CST-15289] fix locale working badly for timezones with negative UTC offset Approved-by: Alisa Ismailati
2 parents 048f26b + 7766dcd commit 1db5098

2 files changed

Lines changed: 29 additions & 8 deletions

File tree

src/app/shared/date.util.spec.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { dateToString, dateToNgbDateStruct, dateToISOFormat, isValidDate, yearFromString } from './date.util';
1+
import {
2+
dateToString,
3+
dateToNgbDateStruct,
4+
dateToISOFormat,
5+
isValidDate,
6+
yearFromString,
7+
localeDate
8+
} from './date.util';
29

310
describe('Date Utils', () => {
411

@@ -104,4 +111,15 @@ describe('Date Utils', () => {
104111
expect(yearFromString('test')).toBeNull();
105112
});
106113
});
114+
115+
describe('localeDate', () => {
116+
it('should return the date in the current locale', () => {
117+
expect(localeDate('2022-06-03', 'en')).toEqual('June 3, 2022');
118+
expect(localeDate('2022-06-03', 'it')).toEqual('3 giugno 2022');
119+
expect(localeDate('2022-06', 'en')).toEqual('June 2022');
120+
expect(localeDate('2022-06', 'it')).toEqual('giugno 2022');
121+
expect(localeDate('2022', 'en')).toEqual('2022');
122+
expect(localeDate('2022', 'it')).toEqual('2022');
123+
});
124+
});
107125
});

src/app/shared/date.util.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -108,16 +108,19 @@ export function yearFromString(date: string) {
108108
}
109109

110110

111-
export function localeDate(date: string, locale?: string) {
111+
export function localeDate(date: string, locale?: string): string {
112+
const parts = date.split('-').map(part => parseInt(part, 10));
113+
const year = parts[0];
114+
const month = parts.length > 1 ? parts[1] - 1 : 0; // Default to January if no month
115+
const day = parts.length > 2 ? parts[2] : 1; // Default to the first day if no day
112116

113-
const tokens = date.split('-').length;
117+
const dateObj = new Date(year, month, day);
114118

115-
const options: Intl.DateTimeFormatOptions = {
119+
const options: Intl.DateTimeFormatOptions = {
116120
year: 'numeric',
117-
month: tokens >= 2 ? 'long' : undefined,
118-
day: tokens >= 3 ? 'numeric' : undefined,
121+
month: parts.length > 1 ? 'long' : undefined, // Show month only if provided
122+
day: parts.length > 2 ? 'numeric' : undefined, // Show day only if provided
119123
};
120124

121-
return new Date(date).toLocaleDateString(locale, options);
122-
125+
return dateObj.toLocaleDateString(locale, options);
123126
}

0 commit comments

Comments
 (0)