Skip to content

Commit d3acf18

Browse files
feat(material-luxon-adapter): add option to set zone (#33579)
Add zone option to be able to change the zone through MAT_LUXON_DATE_ADAPTER_OPTIONS.
1 parent cdcbd89 commit d3acf18

3 files changed

Lines changed: 169 additions & 23 deletions

File tree

‎src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts‎

Lines changed: 116 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {TestBed} from '@angular/core/testing';
1111
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
1212
import {CalendarSystem, DateTime, FixedOffsetZone, Settings} from 'luxon';
1313
import {LuxonDateModule} from './index';
14-
import {MAT_LUXON_DATE_ADAPTER_OPTIONS} from './luxon-date-adapter';
14+
import {LuxonDateAdapter, MAT_LUXON_DATE_ADAPTER_OPTIONS} from './luxon-date-adapter';
1515

1616
const JAN = 1,
1717
FEB = 2,
@@ -418,7 +418,7 @@ describe('LuxonDateAdapter', () => {
418418
expect(clone.toISO()).toEqual(date.toISO());
419419
});
420420

421-
it('should respect timezone on clone', () => {
421+
it('should respect timeZone on clone', () => {
422422
const dateLocal = DateTime.local(2017, JAN, 1);
423423
const dateInCet = dateLocal.setZone('Europe/Budapest');
424424
const cloneInCet = adapter.clone(dateInCet);
@@ -757,7 +757,7 @@ describe('LuxonDateAdapter with LOCALE_ID override', () => {
757757
});
758758

759759
describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override', () => {
760-
let adapter: DateAdapter<DateTime>;
760+
let adapter: LuxonDateAdapter;
761761

762762
beforeEach(() => {
763763
TestBed.configureTestingModule({
@@ -770,7 +770,7 @@ describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override', () =>
770770
],
771771
});
772772

773-
adapter = TestBed.inject(DateAdapter);
773+
adapter = TestBed.inject(DateAdapter) as LuxonDateAdapter;
774774
});
775775

776776
describe('use UTC', () => {
@@ -789,14 +789,38 @@ describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override', () =>
789789
});
790790

791791
it('should parse dates to UTC', () => {
792-
const date = adapter.parse('1/2/2017', 'LL/dd/yyyy')!;
792+
const date = adapter.parse('1/2/2017', 'L/d/yyyy')!;
793793
expect(date.toISO()).toBe(date.toUTC().toISO());
794794
});
795795

796796
it('should return UTC date when deserializing', () => {
797797
const date = adapter.deserialize('1985-04-12T23:20:50.52Z')!;
798798
expect(date.toISO()).toBe(date.toUTC().toISO());
799799
});
800+
801+
it('setting timeZone should throw an error when useUtc is true', () => {
802+
expect(() => adapter.setTimeZone('Europe/Budapest')).toThrowError(
803+
'Cannot set timeZone if the useUtc option is set to true.',
804+
);
805+
});
806+
});
807+
});
808+
809+
describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS useUtc and timeZone override same time', () => {
810+
it('setting useUtc and timeZone same time should throw an Error', () => {
811+
TestBed.configureTestingModule({
812+
imports: [LuxonDateModule],
813+
providers: [
814+
{
815+
provide: MAT_LUXON_DATE_ADAPTER_OPTIONS,
816+
useValue: {useUtc: true, firstDayOfWeek: 1, timeZone: 'Europe/Budapest'},
817+
},
818+
],
819+
});
820+
821+
expect(() => TestBed.inject(DateAdapter)).toThrowError(
822+
'Cannot set timeZone if the useUtc option is set to true.',
823+
);
800824
});
801825
});
802826

@@ -835,6 +859,93 @@ describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override for defa
835859
});
836860
});
837861

862+
describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS timeZone override', () => {
863+
let adapter: DateAdapter<DateTime>;
864+
865+
const timeZone = 'UTC-12';
866+
867+
beforeEach(() => {
868+
TestBed.configureTestingModule({
869+
imports: [LuxonDateModule],
870+
providers: [
871+
{
872+
provide: MAT_LUXON_DATE_ADAPTER_OPTIONS,
873+
useValue: {firstDayOfWeek: 1, timeZone},
874+
},
875+
],
876+
});
877+
878+
adapter = TestBed.inject(DateAdapter);
879+
});
880+
881+
describe(`use ${timeZone} timeZone`, () => {
882+
it('should create Luxon date in specified timeZone', () => {
883+
const date = adapter.createDate(2017, 0, 5);
884+
expect(date.zone.name).toEqual(timeZone);
885+
expect(date.toISO()).toEqual(DateTime.local(2017, JAN, 5, {zone: timeZone}).toISO());
886+
});
887+
888+
it('should create today in specified timeZone', () => {
889+
const today = adapter.today();
890+
expect(today.zone.name).toEqual(timeZone);
891+
});
892+
893+
it('should parse dates to specified timeZone', () => {
894+
const date = adapter.parse('1/2/2017', 'L/d/yyyy')!;
895+
expect(date.zone.name).toEqual(timeZone);
896+
expect(date.toISO()).toBe(DateTime.local(2017, JAN, 2, {zone: timeZone}).toISO());
897+
});
898+
899+
it('should return date when deserializing in specified timeZone', () => {
900+
const date = adapter.deserialize('1985-04-12T23:20:50.52Z')!;
901+
expect(date.zone.name).toEqual(timeZone);
902+
expect(date.toISO()).toBe('1985-04-12T11:20:50.520-12:00');
903+
});
904+
});
905+
});
906+
907+
describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS timeZone override programmatically', () => {
908+
let adapter: LuxonDateAdapter;
909+
910+
const timeZone = 'UTC-12';
911+
912+
beforeEach(() => {
913+
TestBed.configureTestingModule({
914+
imports: [LuxonDateModule],
915+
providers: [
916+
{
917+
provide: MAT_LUXON_DATE_ADAPTER_OPTIONS,
918+
useValue: {firstDayOfWeek: 1, timeZone},
919+
},
920+
],
921+
});
922+
923+
adapter = TestBed.inject(DateAdapter) as LuxonDateAdapter;
924+
});
925+
926+
describe(`use ${timeZone} timeZone`, () => {
927+
it('should return correct timeZone after setting zone programmatically', () => {
928+
const date = adapter.createDate(2017, 0, 5);
929+
expect(date.zone.name).toEqual(timeZone);
930+
931+
const newTimeZone = 'UTC-6';
932+
adapter.setTimeZone(newTimeZone);
933+
934+
const dateAfterZoneChange = adapter.createDate(2017, 0, 5);
935+
expect(dateAfterZoneChange.zone.name).toEqual(newTimeZone);
936+
937+
const today = adapter.today();
938+
expect(today.zone.name).toEqual(newTimeZone);
939+
940+
const parsedDate = adapter.parse('1/2/2017', 'L/d/yyyy')!;
941+
expect(parsedDate.zone.name).toEqual(newTimeZone);
942+
943+
const deserializedDate = adapter.deserialize('1985-04-12T23:20:50.52Z')!;
944+
expect(deserializedDate.zone.name).toEqual(newTimeZone);
945+
});
946+
});
947+
});
948+
838949
function assertValidDate(adapter: DateAdapter<DateTime>, d: DateTime | null, valid: boolean) {
839950
expect(adapter.isDateInstance(d))
840951
.not.withContext(`Expected ${d} to be a date instance`)

‎src/material-luxon-adapter/adapter/luxon-date-adapter.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
DateTime as LuxonDateTime,
1313
Info as LuxonInfo,
1414
DateTimeOptions as LuxonDateTimeOptions,
15+
LocaleOptions as LuxonLocaleOptions,
1516
CalendarSystem as LuxonCalendarSystem,
1617
} from 'luxon';
1718

@@ -23,6 +24,13 @@ export interface MatLuxonDateAdapterOptions {
2324
*/
2425
useUtc: boolean;
2526

27+
/**
28+
* Sets the timeZone of DateTime objects.
29+
* Changing this will change how Angular Material components like DatePicker output dates.
30+
* Throws an error if the useUtc parameter is set to true and the timeZone is also provided.
31+
*/
32+
timeZone?: string;
33+
2634
/**
2735
* Sets the first day of week.
2836
* Changing this will change how Angular Material components like DatePicker shows start of week.
@@ -63,6 +71,7 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
6371
private _useUTC: boolean;
6472
private _firstDayOfWeek: number | undefined;
6573
private _defaultOutputCalendar: LuxonCalendarSystem;
74+
private _timeZone?: string;
6675

6776
constructor() {
6877
super();
@@ -75,6 +84,7 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
7584
this._useUTC = !!options?.useUtc;
7685
this._firstDayOfWeek = options?.firstDayOfWeek;
7786
this._defaultOutputCalendar = options?.defaultOutputCalendar || 'gregory';
87+
this.setTimeZone(options?.timeZone);
7888
this.setLocale(dateLocale || LuxonDateTime.local().locale);
7989
}
8090

@@ -122,7 +132,7 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
122132
}
123133

124134
getYearName(date: LuxonDateTime): string {
125-
return date.toFormat('yyyy', this._getOptions());
135+
return date.toFormat('yyyy', this._getLocaleOptions());
126136
}
127137

128138
getFirstDayOfWeek(): number {
@@ -135,14 +145,12 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
135145

136146
clone(date: LuxonDateTime): LuxonDateTime {
137147
return LuxonDateTime.fromObject(date.toObject(), {
138-
...this._getOptions(),
148+
...this._getLocaleOptions(),
139149
zone: date.zone,
140150
});
141151
}
142152

143153
createDate(year: number, month: number, date: number): LuxonDateTime {
144-
const options = this._getOptions();
145-
146154
if (month < 0 || month > 11) {
147155
throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
148156
}
@@ -153,8 +161,8 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
153161

154162
// Luxon uses 1-indexed months so we need to add one to the month.
155163
const result = this._useUTC
156-
? LuxonDateTime.utc(year, month + 1, date, options)
157-
: LuxonDateTime.local(year, month + 1, date, options);
164+
? LuxonDateTime.utc(year, month + 1, date, this._getLocaleOptions())
165+
: LuxonDateTime.local(year, month + 1, date, this._getDateTimeOptions());
158166

159167
if (!this.isValid(result)) {
160168
throw Error(`Invalid date "${date}". Reason: "${result.invalidReason}".`);
@@ -164,13 +172,13 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
164172
}
165173

166174
today(): LuxonDateTime {
167-
const options = this._getOptions();
168-
169-
return this._useUTC ? LuxonDateTime.utc(options) : LuxonDateTime.local(options);
175+
return this._useUTC
176+
? LuxonDateTime.utc(this._getLocaleOptions())
177+
: LuxonDateTime.local(this._getDateTimeOptions());
170178
}
171179

172180
parse(value: unknown, parseFormat: string | string[]): LuxonDateTime | null {
173-
const options: LuxonDateTimeOptions = this._getOptions();
181+
const options: LuxonDateTimeOptions = this._getDateTimeOptions();
174182

175183
if (typeof value == 'string' && value.length > 0) {
176184
const iso8601Date = LuxonDateTime.fromISO(value, options);
@@ -217,15 +225,15 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
217225
}
218226

219227
addCalendarYears(date: LuxonDateTime, years: number): LuxonDateTime {
220-
return date.reconfigure(this._getOptions()).plus({years});
228+
return date.reconfigure(this._getLocaleOptions()).plus({years});
221229
}
222230

223231
addCalendarMonths(date: LuxonDateTime, months: number): LuxonDateTime {
224-
return date.reconfigure(this._getOptions()).plus({months});
232+
return date.reconfigure(this._getLocaleOptions()).plus({months});
225233
}
226234

227235
addCalendarDays(date: LuxonDateTime, days: number): LuxonDateTime {
228-
return date.reconfigure(this._getOptions()).plus({days});
236+
return date.reconfigure(this._getLocaleOptions()).plus({days});
229237
}
230238

231239
toIso8601(date: LuxonDateTime): string {
@@ -238,7 +246,7 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
238246
* string into null. Returns an invalid date for all other values.
239247
*/
240248
override deserialize(value: unknown): LuxonDateTime | null {
241-
const options = this._getOptions();
249+
const options = this._getDateTimeOptions();
242250
let date: LuxonDateTime | undefined;
243251
if (value instanceof Date) {
244252
date = LuxonDateTime.fromJSDate(value, options);
@@ -320,15 +328,34 @@ export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> {
320328
}
321329

322330
override addSeconds(date: LuxonDateTime, amount: number): LuxonDateTime {
323-
return date.reconfigure(this._getOptions()).plus({seconds: amount});
331+
return date.reconfigure(this._getLocaleOptions()).plus({seconds: amount});
332+
}
333+
334+
/**
335+
* Sets the timeZone of DateTime objects.
336+
* Changing this will change how Angular Material components like DatePicker output dates.
337+
* Throws an error if the useUtc parameter is set to true and the timeZone is also provided.
338+
*/
339+
setTimeZone(timeZone?: string) {
340+
if (this._useUTC && timeZone) {
341+
throw Error(`Cannot set timeZone if the useUtc option is set to true.`);
342+
}
343+
this._timeZone = timeZone;
324344
}
325345

326-
/** Gets the options that should be used when constructing a new `DateTime` object. */
327-
private _getOptions(): LuxonDateTimeOptions {
346+
/** Gets the Locale options that should be used when Luxon expects a LocaleOptions parameter. */
347+
private _getLocaleOptions(): LuxonLocaleOptions {
328348
return {
329-
zone: this._useUTC ? 'utc' : undefined,
330349
locale: this.locale,
331350
outputCalendar: this._defaultOutputCalendar,
332351
};
333352
}
353+
354+
/** Gets the DateTime options that should be used when Luxon expects a DateTimeOptions, e.g. when constructing/parsing a `DateTime` object. */
355+
private _getDateTimeOptions(): LuxonDateTimeOptions {
356+
return {
357+
...this._getLocaleOptions(),
358+
zone: this._useUTC ? 'utc' : this._timeZone,
359+
};
360+
}
334361
}

‎src/material/datepicker/datepicker.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,14 @@ bootstrapApplication(MyApp, {
430430
});
431431
```
432432

433+
You can also change the default behaviour to parse and handle dates as any desired timeZone by passing `timeZone` into `provideLuxonDateAdapter`:
434+
435+
```ts
436+
bootstrapApplication(MyApp, {
437+
providers: [provideLuxonDateAdapter(undefined, {timeZone: 'UTC+2'})]
438+
});
439+
```
440+
433441
It is also possible to create your own `DateAdapter` that works with any date format your app
434442
requires. This is accomplished by subclassing `DateAdapter` and providing your subclass as the
435443
`DateAdapter` implementation. You will also want to make sure that the `MAT_DATE_FORMATS` provided

0 commit comments

Comments
 (0)