Mat-DatePicker common problem and solutions
- Posted by Muthukumar Dharmar
- Categories Angular
- Date April 25, 2020
In this post, we will address couple of common date field issues that we face when using Angular Material date picker and will look in to the solution for several cases.
Lets Begin
Problem:
Date display format, for example in india we use the date month year format and the angular material datepicker has the default format of MM/DD/YYYY.
Solution:
The solution is pretty simple and strait forward, we can resolve this display format issue by changing the LOCALE settings.
As of now angular material date adapter does not support the locale en-IN, hope this will be included soon, for now we will be using the en-GB which serves the same purpose.
Cool, we are now able to display the date in expected format. But still there is a problem
Problem:
Now we displayed the date in correct format. What next? Yes, obviously we have to store the data into the database, for which we will be passing the data model to a web API.
Here is the next problem, in order to pass the data in the wire, model object has to be serialized as JSON String right?
See, the date in memory is 14th April 2020 without time selection it is 00:00:00 but it includes the time zone as GMT+0530 (IST)
The serialization process converts the date to UTC and it subtracts 5:30 hrs. Now the output passed on to API is 13th April 2020 with 18:30 UTC.
Solution 1:
This is not at all an issue, if we are storing this value in UTC format and the API returns the same format.
Though the date from API is UTC, when we bind it to date picker it will automatically apply the locale and will display the correct Value.
Solution 2: (Preferred approach)
Since we don’t need the time part we can simply tell the date adapter to use the UTC format as default. in this case date in memory is already in UTC and there is no issue of locale conversion.
Now you might be wondering if we remove the MAT_DATE_LOCALE provider, we will lose the display format. right? Yes, for this approach we are going to remove the locale provider and specify a custom format settings as below.
I hope this article is helpful, please share your valuable feedback in the comment section below.
Tag:Angular, Mat-DatePicker
1 Comment
Simple and well explained.