Skip to content

Commit 26832a4

Browse files
committed
fix: Normalize literal before dayPeriod
1 parent d434b6d commit 26832a4

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

packages/@internationalized/date/src/DateFormatter.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,18 @@ export class DateFormatter implements Intl.DateTimeFormat {
3434

3535
/** Formats a date to an array of parts such as separators, numbers, punctuation, and more. */
3636
formatToParts(value: Date): Intl.DateTimeFormatPart[] {
37-
return this.formatter.formatToParts(value);
37+
const parts = this.formatter.formatToParts(value);
38+
39+
const literalBeforeDayPeriodIndex =
40+
parts.findIndex((p) => p.type === "dayPeriod") - 1;
41+
if (literalBeforeDayPeriodIndex >= 0) {
42+
const normalizedParts = parts.map((p, i) =>
43+
i === literalBeforeDayPeriodIndex ? { ...p, value: " " } : p,
44+
);
45+
return normalizedParts;
46+
}
47+
48+
return parts;
3849
}
3950

4051
/** Formats a date range as a string. */

packages/@internationalized/date/tests/DateFormatter.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,17 @@ describe('DateFormatter', function () {
4242
]);
4343
});
4444

45+
it('should format to parts with space as literal before am/pm', function () {
46+
let formatter = new DateFormatter('en-US', {timeStyle: 'short'});
47+
expect(formatter.formatToParts(new Date(2020, 1, 3, 13, 0))).toEqual([
48+
{type: 'hour', value: '1'},
49+
{type: 'literal', value: ':'},
50+
{type: 'minute', value: '00'},
51+
{type: 'literal', value: ' '},
52+
{type: 'dayPeriod', value: 'PM'}
53+
]);
54+
});
55+
4556
it('should format a range', function () {
4657
let formatter = new DateFormatter('en-US');
4758
// Test fallback

0 commit comments

Comments
 (0)