Colls,我有一个代码应该创建一个sToday变量,它返回时间戳,如“DD_MM_YYYY_HH_MI_SS”:
var today = new Date();
var CurrentDay = today.getDay();
var CurrentMonth = today.getMonth();
var CurrentHours = today.getHours();
var CurrentMin = today.getMinutes();
var CurrentSec = today.getSeconds();
if (CurrentDay < 10)
sToday = "0"+today.getDay().toString();
else
sToday = today.getDay().toString();
if(CurrentMonth<10)
sToday += "_0"+today.getMonth().toString();
else
sToday += "_"+today.getMonth().toString();
sToday += "_"+today.getYear().toString();
if (CurrentHours<10)
sToday += "_0"+today.getHours().toString();
else
sToday += "_"+today.getHours().toString();
if (CurrentMin<10)
sToday += "_0"+today.getMinutes().toString();
else
sToday += "_"+today.getMinutes().toString();
if (CurrentSec<10)
sToday += "_0"+today.getSeconds().toString();
else
sToday += "_"+today.getSeconds().toString();
但是当我运行它13.04.2012 20:20:14(我的电脑时间)然后我收到05_03_2012_20_20_14。 如何解决这个问题并收到13_04_2012_20_20_14?
答案 0 :(得分:1)
.getDay
返回星期几(星期日为0,星期一为1,......)。您想改用.getDate
。
function tw(n){
return (n < 10 ? '0' : '') + n.toString();
}
var today = new Date();
var sToday = (tw(today.getDate()) + '_' + tw(today.getMonth()+1) + '_' +
today.getYear().toString() + '_' + tw(today.getHours()) +
'_' + tw(today.getMinutes()) + '_' + tw(today.getSeconds()));
答案 1 :(得分:0)
getDate
返回日期1-31。 getDay
返回0-6周的一天,0表示星期日。
getMonth
返回0-11月,因此您需要为该值添加1。
而不是立即打印日期,月份,而是打印日,月 - 1。
将您的代码更改为:
if (CurrentDay < 10)
sToday = "0"+today.getDate().toString();
else
sToday = today.getDate().toString();
if(CurrentMonth<10)
sToday += "_0"+ (today.getMonth() + 1).toString();
else
sToday += "_"+(today.getMonth() + 1).toString();
答案 2 :(得分:0)
当天使用.getDate并在月份中添加1(月份从零开始,因此1月份为0,2月份为1,依此类推......)