Search code examples
javascriptparsingdateuser-inputdatejs

How can I make Datejs return only the year when only the year is given?


I'm using Datjs to take a date from a user and convert it to a format suitable for storage in my database. When I supply a date with month, day, and year, I get just what I want, the date formatted year-month-day:

    var d1 = Date.parse('02/22/1984');
    console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-02-22'

However, when I give a year only, I get back the same year, followed by today's month and day:

    var d1 = Date.parse('1984');
    console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-12-19'

What can I do to ensure that when the user types in nothing but a year that just that year is returned in the following format

    1984-00-00

Likewise, if only the month and year are give I'd like it formatted like this:

    1984-02-00

Solution

  • Datejs returns a JavaScript Date object. This object is intended to represent a point in time and a point in time necessarily includes the month and day. When not provided, Datejs defaults these values to the current month and day. If you don't want to display that information, then change your formatting pattern:

    var d1 = Date.parse('1984');
    console.log(d1.toString('yyyy')); // prints 1984
    

    If you need to change the pattern based on what the user originally entered, then you need to save that information, so that you know what to print later.

    A simple example follows:

    function DatePrinter(input) {
        var s = input.split("/").length;
        this.fmt = ["dd", "MM", "yyyy"].slice(3 - s).reverse().join("-");
        this.date = Date.parse(input);
    }
    
    DatePrinter.prototype.toString = function() {
        return (this.date.toString(this.fmt) + "-00-00").slice(0, 10);
    }
    

    Some tests:

    new DatePrinter("02/22/1984").toString() // "1984-02-22"
    new DatePrinter("02/1984").toString() // "1984-02-00"
    new DatePrinter("1984").toString() // "1984-00-00"