How to get 2 digit year w/ Javascript ?



  • 3 Answer(s)

    The one line in the code below which is the most accurate answer for this question,

    //pull the last two digits of the year
    //logs to console
    //creates a new date object (has the current date and time by default)
    //gets the full year from the date object (currently 2017)
    //converts the variable to a string
    //gets the substring backwards by 2 characters (last two characters)
    console.log(new Date().getFullYear().toString().substr(-2));
    

    Example for format the date and time ,

    In javascript,

    //A function for formatting a date to MMddyy
    function formatDate(d)
    {
        //get the month
        var month = d.getMonth();
        //get the day
        //convert day to string
        var day = d.getDate().toString();
        //get the year
        var year = d.getFullYear();
     
        //pull the last two digits of the year
        year = year.toString().substr(-2);
     
        //increment month by 1 since it is 0 indexed
        //converts month to a string
        month = (month + 1).toString();
     
        //if month is 1-9 pad right with a 0 for two digits
        if (month.length === 1)
        {
            month = "0" + month;
        }
     
        //if day is between 1-9 pad right with a 0 for two digits
        if (day.length === 1)
        {
            day = "0" + day;
        }
     
        //return the string "MMddyy"
        return month + day + year;
    }
     
    var d = new Date();
    console.log(formatDate(d));
    
    Answered on January 2, 2019.
    Add Comment

    The date object is here,

    date.getFullYear().toString().substr(2,2);
    
    

    It gives the number in a string format. But in order to get the integer is, just bundle up it inside of the function named parselnt().

    var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);
    
    

    Here is an example for current year,

    var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));
    
    
    Answered on January 2, 2019.
    Add Comment

    Use the code given below,

    var currentYear = (new Date()).getFullYear();
    var twoLastDigits = currentYear%100;
     
    var formatedTwoLastDigits = "";
     
    if (twoLastDigits <10 ) {
        formatedTwoLastDigits = "0" + twoLastDigits;
    } else {
        formatedTwoLastDigits = "" + twoLastDigits;
    }
    
    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.