Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a valid empty date in Moment js?

So, I am using an Angular material datepicker which only helps me select a month and a year. https://material.angular.io/components/datepicker/overview#watching-the-views-for-changes-on-selected-years-and-months

However, the functionality doesn't quite work as expected unless you do something like this- date = new FormControl(moment()); (You are allowed to select the day as well, apart from the month and the year.)

Now moment() as we know just returns the current date and time. My main objective is to display existing user details in a form for an application. However, the user can edit the form after it's loaded. One of those fields is a Material datepicker. Now, it's not a required field, so I don't always receive a valid response from the backend. When the response is a date, there are absolutely no issues. But whenever I receive a null value, that's where the main problem arises.

I had a look at the Moment.js docs (https://momentjs.com/docs/) and it clearly states that moment(null) and moment("") are both invalid dates. And hence once I use either of the two to initialize the datepicker, the datepicker doesn't allow me to select a date in the editable mode at all.

How can I set a valid, empty date using moment() which won't interfere with the datepicker's functionality?

like image 704
Snigdho Bhattacharya Avatar asked Apr 17 '19 18:04

Snigdho Bhattacharya


People also ask

How do you set a moment in date?

moment(). set('year', 2013); moment(). set('month', 3); // April moment(). set('date', 1); moment().

How do I know if a moment date is valid?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

How can I remove time from date with MomentJS?

We can remove the time portion from a date with the startOf method. We pass in a date with the hour and minutes set into the moment function. Then we call startOf with the 'day' argument to get return a moment object with the time set to midnight of the same date.


2 Answers

We had the same issue in our project and we fixed it by adding a ternary condition for the value of the date picker. const dateValue = value ? moment(value) : null; if the value exists we create a moment object from it, if not it should be null.

like image 135
MKrup Avatar answered Sep 17 '22 22:09

MKrup


If you use the moment adapter and moment dates, you should set your component's date variable to null, and not to moment(null). Internally, the datepicker will ask the adapter if the date is valid but moment(null).isValid() returns false thus triggering the parse validator that will return an error.

like image 25
Fabian Vilers Avatar answered Sep 17 '22 22:09

Fabian Vilers