Search code examples
javascriptdatejodatimemomentjsdatejs

Date and time without timestamp in Javascript


In Javascript I need to work with the concepts of date, time and "date and time " without referring to a particular point in time. This is exactly the same semantics that joda time's LocalDate and LocalTime provide in Java. I've been briefly looking at Date.js and moment.js, but both libraries seem to build on the Date object, which represents a point in time. Is there any javascript library that provides what I need?

Use case:

There is a model entity -a coupon- which has an expiration date (joda time's LocalDate). I want to compare that date with today's date, so I need a representation of today's date (actually a string in yyyy-mm-dd format would do). I know that today's date, and hence the result of the comparison too, will depend on the timezone settings of the browser's but that's not a problem.


Solution

  • I've started a few times on a JavaScript library with similar API to Noda Time / Joda Time / Java 8. I definitely see value in that. However, there's nothing out there as of yet, as far as I know. There are other reasons that make the Date object less than ideal. I'll try to remember to update this post when/if I ever get a new library off the ground, or if I learn of one created by someone else.

    In the mean time, the easiest thing would be to use moment.js:

    var expDateString = "2015-06-30";
    var exp = moment(expDateString, "YYYY-MM-DD");
    var now = moment();
    if (exp.isAfter(now))
       // expired
    else
       // valid
    

    You could also do this with plain JavaScript, but there are some gotchas with parsing behavior. Moment is easier.