Skip to content Skip to sidebar Skip to footer

Formatting Javascript String To Have 03 Not 3?

I have a Javascript that opens today file in html. function openToday() { var today = new Date(); var strYear = today.getFullYear(); var strMonth = today.getMonth();

Solution 1:

Check to see if the month is only 1 character long (or alternatively, < 9). Then prepend the 0!

By length

var strMonth = today.getMonth();

if(strMonth .length == 1){
    strMonth = "0" + strMonth ;
}

By number

var strMonth = today.getMonth();

if(strMonth< 10){
    strMonth= "0" + strMonth;
}

Probably want to avoid prefixing the variable with str as Javascript doesn't explicitly define types, and can confuse the code. For example, saying if strMonth < 10 is fine logic wise, but maintainance wise it's confusing to manage.

Another Way!

var strMonth = "0" + today.getMonth();
strMonth = strMonth.substring(strMonth.length-2, 2);

Solution 2:

You could create a general-purpose padding function:

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

pad(today.getDay(), 2); // If today was '3', would print '03'

Solution 3:

I made a function for that some time ago.

var strURL = "file:/time/"+strYear+"/"+convertDateToString(date.getMonth()+1)+"/" +   strYear+"_"+convertDateToString(date.getMonth()+1)+"_"+strDay+ "/" +   strYear+"_"+strMonth+"_"+strDay+".html";

The function:

/*
Method: convertDateToString
Input: Integer  
Returns: a string from a number and adds a 0 when the number is smaller than 10

Examples: 1 => 01, 8 => 08, 11 => 11
*/ 
function convertDateToString(number){   
  return (number < 10 ) ? 0+number.toString() : number.toString();
}

Good luck!


Solution 4:

var strMonth = today.getMonth();
if(strMonth.length == 1){
   strMonth = '0' + strMonth;
}

Solution 5:

Perhaps you may extend it to allow for padding strings like this:

function pad(number, length, padWith) {
    padWith = (typeof padWith!=='undefined) ? padWith : '0';
    var str = '' + number;
    while (str.length < length) {
        str = padWith + str;
    }
    return str;
}

Post a Comment for "Formatting Javascript String To Have 03 Not 3?"