显示昨天日期和今天日期的Javascript代码

cat*_*008 40 javascript date

如何在我的文本框中显示昨天的日期和同一时间,今天的日期在?

我有这个home.php,我昨天显示日期(用户不能修改此只读)和今天的日期(用户必须今天输入日期).当明天到来并且用户访问家庭.php /他将看到昨天输入的日期,并将在明天再次输入日期.

EG:Day1(2011年3月30日)昨天的日期:2011年3月29日.(不可编辑的文本框)今天输入日期:(我将输入..)2011年3月30日.

第2天(2011年3月31日)昨天的日期:2011年3月30日.(不可编辑的文本框)自动,这将在点击home.php时出现今天输入日期:(我将输入..)2011年3月31日.

等等..

我需要一个不接受错误日期格式的验证,格式必须是:01-Mar-11如何做到这一点?:(

Rob*_*obG 107

昨天的日期只是今天的日期而不是一个,所以:

var d = new Date();
d.setDate(d.getDate() - 1);
Run Code Online (Sandbox Code Playgroud)

如果今天是4月1日,那么它将被定为4月0日,转换为3月31日.

既然你也想做其他一些事情,这里有一些功能:

// Check if d is a valid date
// Must be format year-month name-date
// e.g. 2011-MAR-12 or 2011-March-6
// Capitalisation is not important
function validDate(d) {
  var bits = d.split('-');
  var t = stringToDate(d);
  return t.getFullYear() == bits[0] && 
         t.getDate() == bits[2];
}

// Convert string in format above to a date object
function stringToDate(s) {
  var bits = s.split('-');
  var monthNum = monthNameToNumber(bits[1]);
  return new Date(bits[0], monthNum, bits[2]);
}

// Convert month names like mar or march to 
// number, capitalisation not important
// Month number is calendar month - 1.
var monthNameToNumber = (function() {
  var monthNames = (
     'jan feb mar apr may jun jul aug sep oct nov dec ' +
     'january february march april may june july august ' +
     'september october november december'
     ).split(' ');

  return function(month) {
    var i = monthNames.length;
    month = month.toLowerCase(); 

    while (i--) {
      if (monthNames[i] == month) {
        return i % 12;
      }
    }
  }
}());

// Given a date in above format, return
// previous day as a date object
function getYesterday(d) {
  d = stringToDate(d);
  d.setDate(d.getDate() - 1)
  return d;
}

// Given a date object, format
// per format above
var formatDate = (function() {
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  function addZ(n) {
    return n<10? '0'+n : ''+n;
  }
  return function(d) {
    return d.getFullYear() + '-' + 
           months[d.getMonth()] + '-' + 
           addZ(d.getDate());
  }
}());

function doStuff(d) {

  // Is it format year-month-date?
  if (!validDate(d)) {
    alert(d + ' is not a valid date');
    return;
  } else {
    alert(d + ' is a valid date');
  }
  alert(
    'Date in was: ' + d +
    '\nDay before: ' + formatDate(getYesterday(d))
  );
}


doStuff('2011-feb-08');
// Shows 2011-feb-08 is a valid date
//       Date in was: 2011-feb-08
//       Day before: 2011-feb-07
Run Code Online (Sandbox Code Playgroud)


ori*_*dam 39

一个班轮:

var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000
Run Code Online (Sandbox Code Playgroud)

  • 它应该是`86400000` (2认同)
  • 实际上,这种类型的微优化在性能方面几乎没有任何好处,并且损害了可读性,我总是使用“24*60*60*1000”来代替。 (2认同)

Cod*_*ker 6

昨天的日期可以计算为,

var prev_date = new Date();
prev_date.setDate(prev_date.getDate() - 1);
Run Code Online (Sandbox Code Playgroud)