格式化Javascript字符串有03不是3? [英] Formatting Javascript string to have 03 not 3?
问题描述
函数openToday()
{
var today = new Date();
var strYear = today.getFullYear();
var strMonth = today.getMonth();
var strDay = today.getDate();
$ b var strURL =file:/ time /+ strYear +_+ strMonth +/+ strYear +_+ strMonth +_+ strDay +/ _ + strDay + HTML。;
alert(strURL);
window.open(strURL,myWindow);
$ / code>
问题是我想要 2011_03_10
,但代码给我 2011_3_10
。
如何格式化Javascript字符串为03而不是3?
编辑
工作正常
$ b
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;
$ b $ var strURL =file:/ time /+ strYear +/+ strMonth +/+ strYear +_+ strMonth +_+ strDay +/+ strYear + _ + strMonth + _ + strDay + HTML;
window.open(strURL,myWindow);
检查月份只有一个字符长(或者,< 9)。然后前置0!
按长度
var strMonth = today.getMonth();
if(strMonth .length == 1){
strMonth =0+ strMonth;
$ b 按编号
var strMonth = today.getMonth();
if(strMonth< 10){
strMonth =0+ strMonth;
$ b $ p
$ b 可能要避免在 str
,因为Javascript没有明确定义类型,可能会混淆代码。例如,如果strMonth <1,则说 10
是很好的逻辑明智的,但保持明智的管理混乱。
另一种方式!
var strMonth =0+ today.getMonth();
strMonth = strMonth.substring(strMonth.length-2,2);
I have a Javascript that opens today file in html.
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 the 2011_03_10
, but the code gives me 2011_3_10
.
How can I format the Javascript string to have 03 not 3?
EDIT
This code works fine
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");
}
解决方案 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);
这篇关于格式化Javascript字符串有03不是3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!