0

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 ?

4

3 回答 3

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()));
于 2012-04-13T16:33:59.513 回答
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();
于 2012-04-13T16:35:43.690 回答
0

使用 .getDate 表示日期并将月份加 1(月份从零开始,因此一月为 0,二月为 1,依此类推...)

于 2012-04-13T16:36:42.127 回答