h2qutc / angular-material-components

Angular Material Library provide extra components for every project
https://h2qutc.github.io/angular-material-components/
MIT License
331 stars 162 forks source link

Update NgxMatDateAdapter to support immutability #122

Open de-don opened 4 years ago

de-don commented 4 years ago

https://github.com/h2qutc/angular-material-components/blob/f147c1c9645167fb170bbca4aa9d91f757c2bb5a/projects/datetime-picker/src/lib/core/date-adapter.ts#L37

Can you change this interface, to return D instead of void, because some libraries (like Luxon) work with immutable objects https://moment.github.io/luxon/docs/manual/tour.html#immutability

chrisch-hh commented 3 years ago

@de-don Did you wrote an Luxon adapter for the datetime-picker? I'm considering Luxon for a project and I'm not sure if I need to implement my own adapter to get the datetime-picker work with Luxon? Maybe you can share your experience.

KelseySheely commented 3 years ago

I was finally able to get this working by forking the repository and updating the setHours, setMinutes, and setSeconds methods to return D. Then I adapted a date adapter based on one I found for MatDatepicker: https://gist.github.com/Zyzle/a9c5daa396882eb155282bcb454b9511

I just added the following methods:

getHour(date: DateTime): number {
    return date.hour;
}

getMinute(date: DateTime): number {
    return date.minute;
}

getSecond(date: DateTime): number {
    return date.second;
}

setHour(date: DateTime, value: number): DateTime {
    return date.set({hour: value});
}

setMinute(date: DateTime, value: number): DateTime {
    return date.set({minute: value});
}

setSecond(date: DateTime, value: number): DateTime {
    return date.set({second: value});
}

You can see my fork and the changes that I made at https://github.com/KelseySheely/angular-material-components.

I think this will cause a breaking change for existing implementations so it may need some consideration before creating a pull request.

Xbloud commented 10 months ago

Upvoting, required for date-fns or Luxon.

lgiraudel commented 10 months ago

I had the same issue with a dayjs adapter, the following code is not working:

const date = dayjs('2023-12-15 12:00:00')
adapter.setHour(date, 3)
expect(adapter.getHour(date)).toBe(3)

Returning the date instance would allow to write this:

let date = dayjs('2023-12-15 12:00:00')
date = adapter.setHour(date, 3)
expect(adapter.getHour(date)).toBe(3)