Handling Invalid dates in moment js

Hey All,

I am using the following code which is also in the JSFiddle here:

//var value_ = "2017-06-09 10:05:21.0"

var value_ = null;

if(moment(value_).isValid()){
                        alert(moment(value_).format('MM/DD/YYYY'));

                       }
                       else  {
                        alert(moment(""));
                       }

Wondering how can I avoid printing invalid date for null value. The null value is returned by the server and I need some way to print something like empty string so that it should stop printing invalid date. Thanks

I’m sorry. What is your issue? It looks like you’re doing exactly what you need. Just don’t send moment an empty string, send it to your output.

Thanks for pointing that out. It worked. I was trying to figure out based on moment js.

1 Like

The problem now I am facing is that on the back end side. On UI, it shows blank date but my date parser on the backend side is unable to parse empty string "". Is there a way I can display null with moment JS without passing empty string?

I am getting Parse exception just like mentioned here because beginning of the string cannot get parsed.

http://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-

simply test in Java if you have an empty string. if yes, create a default, otherwise use the date parser.

Thanks. I set the date to null first and then checked if the date is null or empty string, if it’s true then I again set the date to null otherwise I used the date parser. This thing worked.

I think there isn’t any way to deal with it from moment Js point of view.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.