This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock

Tuesday, May 17, 2016

Date incrementor in JavaScript

I know, this isn't Python, this is JavaScript, but I need to back up this code snippet.

I have an HTML page with a date input box that I need to increment by one day forward or backward. See example here: http://home.chpc.utah.edu/~u0553130/Brian_Blaylock/ksl_ozone_viewer.php

So, I here are some JavaScript functions that change the date input +/- one day.

function pad(number, length) {
    //I just use this to pad the day or month integer with zeros
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function next_day(){
    //                    dec   jan   feb   mar   arp   may   jun   jul   aug   set   oct   nov   dec   jan
    var days_per_month = ["31", "31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31", "31"];
    
    year = parseInt(document.getElementById('dateinput').value.slice(0,4));
    month = parseInt(document.getElementById('dateinput').value.slice(5,7));
    day = parseInt(document.getElementById('dateinput').value.slice(8,10));
        
    if (day < parseInt(days_per_month[month])){
       day = day+1; 
       day = pad(day,2);
       month = pad(month,2);
        }
    else{
        day = '01';
         if (month==12){
            month = '01';
            year = year +1
            year = pad(year,4)
         }
         else{
            month = month + 1;
            month = pad(month,2);     
         }
        
    }
    
    
    document.getElementById('dateinput').value = year+'-'+month+'-'+day
}

function previous_day(){
    //                    dec   jan   feb   mar   arp   may   jun   jul   aug   set   oct   nov   dec
    var days_per_month = ["31", "31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
    
    year = parseInt(document.getElementById('dateinput').value.slice(0,4));
    month = parseInt(document.getElementById('dateinput').value.slice(5,7));
    day = parseInt(document.getElementById('dateinput').value.slice(8,10));
    
    if (day == 1){
       day = days_per_month[month-1];
        if (month==1){
            month = '12';
            year = year -1
            year = pad(year,4)
        }
        else{
          month = month-1;
           month = pad(month,2);     
        }
       
    }
    else{
        day = day-1;
        day = pad(day,2);
        month = pad(month,2);
    }
    
    
    document.getElementById('dateinput').value = year+'-'+month+'-'+day;

}

Note: this doesn't allow for a leap year date.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.