时间戳中的日期不正确,例如DD_MM_YYYY_HH_MI_SS

Incorrect date in TIMESTAMP like DD_MM_YYYY_HH_MI_SS

本文关键字:MM YYYY HH SS MI DD 例如 日期 不正确 时间戳      更新时间:2023-09-26

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 ?

.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()));

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();

使用 .getDate 表示日期并将 1 添加到月份(月份从零开始,所以一月是 0,二月是 1,依此类推......