将 Javascript 字符串格式化为 03 而不是 3?
我有一个 Javascript,可以以 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");
}
问题是我想要 2011_03_10
,但代码给了我 2011_3_10
。 如何将 Javascript 字符串格式化为 03 而不是 3?
编辑
此代码工作正常
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");
}
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
检查月份是否只有 1 个字符长(或者 < 9)。然后在前面加上0!
按长度
按数字
可能希望避免在变量前加上
str
前缀,因为 Javascript 没有明确定义类型,并且可能会混淆代码。例如,如果 strMonth10
逻辑上很好,但维护方面管理起来很混乱。另一种方式!
Check to see if the month is only 1 character long (or alternatively, < 9). Then prepend the 0!
By length
By number
Probably want to avoid prefixing the variable with
str
as Javascript doesn't explicitly define types, and can confuse the code. For example, sayingif strMonth < 10
is fine logic wise, but maintainance wise it's confusing to manage.Another Way!
您可以创建一个通用的填充函数:
You could create a general-purpose padding function:
我前段时间为此做了一个功能。
功能:
祝你好运!
I made a function for that some time ago.
The function:
Good luck!
也许您可以扩展它以允许填充字符串,如下所示:
Perhaps you may extend it to allow for padding strings like this: