Skip to content

Commit

Permalink
Merged in task/dspace-cris-2023_02_x/DSC-1833 (pull request DSpace#2326)
Browse files Browse the repository at this point in the history
[CST-15289] fix locale working badly for timezones with negative UTC offset

Approved-by: Alisa Ismailati
  • Loading branch information
Andrea Barbasso authored and alisaismailati committed Oct 14, 2024
2 parents 048f26b + 7766dcd commit 1db5098
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
20 changes: 19 additions & 1 deletion src/app/shared/date.util.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { dateToString, dateToNgbDateStruct, dateToISOFormat, isValidDate, yearFromString } from './date.util';
import {
dateToString,
dateToNgbDateStruct,
dateToISOFormat,
isValidDate,
yearFromString,
localeDate
} from './date.util';

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

Expand Down Expand Up @@ -104,4 +111,15 @@ describe('Date Utils', () => {
expect(yearFromString('test')).toBeNull();
});
});

describe('localeDate', () => {
it('should return the date in the current locale', () => {
expect(localeDate('2022-06-03', 'en')).toEqual('June 3, 2022');
expect(localeDate('2022-06-03', 'it')).toEqual('3 giugno 2022');
expect(localeDate('2022-06', 'en')).toEqual('June 2022');
expect(localeDate('2022-06', 'it')).toEqual('giugno 2022');
expect(localeDate('2022', 'en')).toEqual('2022');
expect(localeDate('2022', 'it')).toEqual('2022');
});
});
});
17 changes: 10 additions & 7 deletions src/app/shared/date.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,19 @@ export function yearFromString(date: string) {
}


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

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

const options: Intl.DateTimeFormatOptions = {
const options: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: tokens >= 2 ? 'long' : undefined,
day: tokens >= 3 ? 'numeric' : undefined,
month: parts.length > 1 ? 'long' : undefined, // Show month only if provided
day: parts.length > 2 ? 'numeric' : undefined, // Show day only if provided
};

return new Date(date).toLocaleDateString(locale, options);

return dateObj.toLocaleDateString(locale, options);
}

0 comments on commit 1db5098

Please sign in to comment.