Javascript string formatting for 03 not 3?

I have Javascript that opens a file in html today.

function openToday() { var today = new Date(); var strYear = today.getFullYear(); var strMonth = today.getMonth(); var strDay = today.getDate(); var strURL = "file:/time/"+strYear+"/"+strMonth+"/" + strYear+"_"+strMonth+"_"+strDay+ "/" + strYear+"_"+strMonth+"_"+strDay+".html"; alert(strURL); window.open(strURL,"myWindow"); } 

The problem is that I want to have 2011_03_10 , but the code gives me 2011_3_10 . How can I format a Javascript string to have 3 not 3?

EDIT

This code works great

 function openToday() { var today = new Date(); var strYear = today.getFullYear(); var strMonth = today.getMonth(); strMonth += 1; if(strMonth < 10){ strMonth = "0" + strMonth; } var strDay = today.getDate(); if(strDay < 10){ strDay = "0" + strDay; } var strURL = "file:/time/"+strYear+"/"+strMonth+"/" + strYear+"_"+strMonth+"_"+strDay+ "/" + strYear+"_"+strMonth+"_"+strDay+".html"; window.open(strURL,"myWindow"); } 
+4
source share
5 answers

Make sure that the month is only 1 character (or alternatively <9). Then add 0!

By lenght

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

By number

 var strMonth = today.getMonth(); if(strMonth< 10){ strMonth= "0" + strMonth; } 

Perhaps you want to avoid the variable prefix with str , since Javascript does not explicitly define types and can be confusing for the code. For example, saying that if strMonth < 10 is subtle logic, but maintenance is tricky that it confuses management.

Another way!

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

You can create a universal add-on 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' 
+2
source

I made a function for this a while ago.

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

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

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

Perhaps you can expand it to add lines 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; } 
0
source

Source: https://habr.com/ru/post/1343187/


All Articles