Skip to content

Commit

Permalink
fix(js-jods): Propert support for date-only and time-only in mergeDat…
Browse files Browse the repository at this point in the history
…eAndTime 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
  • Loading branch information
joshkel authored Jan 10, 2024
1 parent 2413795 commit 4f78281
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
20 changes: 20 additions & 0 deletions __tests__/js-joda.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { LocalDate, LocalTime, LocalDateTime } from '@js-joda/core';
import JsJodaUtils from "../packages/js-joda/src";

describe("js-joda", () => {
const jsJodaUtils = new JsJodaUtils();

it("Merges a date with a non-time", () => {
const one = LocalDateTime.of(2022, 12, 5, 9, 30);
const two = LocalDate.of(2022, 12, 6);

expect(jsJodaUtils.mergeDateAndTime(one, two)).toEqual(one);
});

it("Merges a non-date with a time", () => {
const one = LocalTime.of(9, 30);
const two = LocalDateTime.of(2022, 12, 5, 9, 30);

expect(jsJodaUtils.mergeDateAndTime(one, two)).toEqual(two);
});
});
15 changes: 10 additions & 5 deletions packages/js-joda/src/js-joda-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,12 +436,17 @@ export default class JsJodaUtils implements IUtils<Temporal> {
}

mergeDateAndTime(date: Temporal, time: Temporal): Temporal {
var qtime = time.query(TemporalQueries.localTime());
if (qtime == null) {
/* istanbul ignore next */
return date;
const qdate = date.query(TemporalQueries.localDate());
const qtime = time.query(TemporalQueries.localTime());
if (qdate && qtime) {
return qdate.atTime(qtime);
} else if (!qdate) {
// A time merged with a non-date gives the original time.
return time;
} else {
return LocalDate.from(date).atTime(LocalTime.from(time));
// A date merged with a non-time gives the original date. We also use
// this as the fallback / error behavior.
return date;
}
}

Expand Down

0 comments on commit 4f78281

Please sign in to comment.