Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a moment contains a time?

Tags:

momentjs

I'm trying to determine if a moment object was instantiated with a time value (in addition to a date). For example:

var date = moment("2014-01-16");
date.format("h:mm a"); // 12:00 am

and

var date2 = moment("2014-01-16 09:30");
date.format("h:mm a"); // 9:30 am

How can I ask date if it contains a time (and not just a default value)?

like image 818
Billy Avatar asked Jan 16 '14 20:01

Billy


1 Answers

Well technically, the constructor that passes only a date IS instantiating it with a time, 12:00:00, even though it is implicit. Even so, here are some possible solutions.

From least safe and least work to most safe and most work:

1) Check if it's exactly equal to 12:00:00 and assume it was not set. Bad approach if your use-case has things happening around midnight often.

2) Don't ever instantiate a moment without explicitly specifying the time.

3) Wrap moment in a custom object, or create an entirely new custom object, capable of representing the null time case (a flag, nullable variable, etc.)

like image 134
Dan Bechard Avatar answered Oct 19 '22 14:10

Dan Bechard