Skip to content

Commit

Permalink
fix: make mergeDateAndTime work across DST changes
Browse files Browse the repository at this point in the history
  • Loading branch information
simonhaenisch committed Mar 31, 2020
1 parent 4e76933 commit 8e5bd63
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
8 changes: 7 additions & 1 deletion src/dates/dates.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,15 @@ describe('Date Helpers', () => {
];

for (const el of data) {
expect(mergeDateAndTime(el.date, new Time(el.time)).format()).toBe(el.expected.format());
expect(mergeDateAndTime(el.date, new Time(el.time))).toBeSameMoment(el.expected);
}
});

it('should work across DST changes', () => {
const date = moment('2020-04-05T00:00:00');

expect(mergeDateAndTime(date, new Time('12:34'))).toBeSameMoment(moment('2020-04-05T12:34:00'));
});
});

describe('minsToMs(number)', () => {
Expand Down
12 changes: 9 additions & 3 deletions src/dates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ declare const moment: typeof import('moment-timezone');
* @param date The date to merge the time into
* @param time The time to merge into the date
*/
export const mergeDateAndTime = (date: Moment | string, time: Time) =>
moment(date)
export const mergeDateAndTime = (date: Moment | string, time: Time) => {
const [hours, minutes] = time
.toString()
.split(':')
.map(Number);

return moment(date)
.startOf('day')
.add(time.valueOf(), 'minutes');
.set({ hours, minutes });
};

/**
* Convert minutes to milliseconds.
Expand Down
4 changes: 2 additions & 2 deletions src/time/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export class Time {
/**
* Add a number of minutes and return a new Time instance with the new value.
*
* This is circular, e. g. when removing 5 minutes from 00:00, the resulting
* time will be 23:55, and when adding 5 mins to 23:55, it will be 00:00.
* This is circular, e. g. when removing 10 minutes from 00:05, the resulting
* time will be 23:55, and when adding 10 mins to 23:55, it will be 00:05.
*/
add(mins: number) {
let newValue = (this.value + mins) % 1440;
Expand Down

0 comments on commit 8e5bd63

Please sign in to comment.