Skip to content

Commit 4f78281

Browse files
authored
fix(js-jods): Propert support for date-only and time-only in mergeDateAndTime method (#653)
* Add support for date-only and time-only to js-joda See mui/mui-x#4703 (comment) (although note that mui-x no longer uses date-io) * Simplify code and address code coverage
1 parent 2413795 commit 4f78281

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

__tests__/js-joda.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { LocalDate, LocalTime, LocalDateTime } from '@js-joda/core';
2+
import JsJodaUtils from "../packages/js-joda/src";
3+
4+
describe("js-joda", () => {
5+
const jsJodaUtils = new JsJodaUtils();
6+
7+
it("Merges a date with a non-time", () => {
8+
const one = LocalDateTime.of(2022, 12, 5, 9, 30);
9+
const two = LocalDate.of(2022, 12, 6);
10+
11+
expect(jsJodaUtils.mergeDateAndTime(one, two)).toEqual(one);
12+
});
13+
14+
it("Merges a non-date with a time", () => {
15+
const one = LocalTime.of(9, 30);
16+
const two = LocalDateTime.of(2022, 12, 5, 9, 30);
17+
18+
expect(jsJodaUtils.mergeDateAndTime(one, two)).toEqual(two);
19+
});
20+
});

packages/js-joda/src/js-joda-utils.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -436,12 +436,17 @@ export default class JsJodaUtils implements IUtils<Temporal> {
436436
}
437437

438438
mergeDateAndTime(date: Temporal, time: Temporal): Temporal {
439-
var qtime = time.query(TemporalQueries.localTime());
440-
if (qtime == null) {
441-
/* istanbul ignore next */
442-
return date;
439+
const qdate = date.query(TemporalQueries.localDate());
440+
const qtime = time.query(TemporalQueries.localTime());
441+
if (qdate && qtime) {
442+
return qdate.atTime(qtime);
443+
} else if (!qdate) {
444+
// A time merged with a non-date gives the original time.
445+
return time;
443446
} else {
444-
return LocalDate.from(date).atTime(LocalTime.from(time));
447+
// A date merged with a non-time gives the original date. We also use
448+
// this as the fallback / error behavior.
449+
return date;
445450
}
446451
}
447452

0 commit comments

Comments
 (0)