尝试使用Moment.js添加日期并获得奇怪的结果

时间:2015-10-16 00:19:16

标签: javascript momentjs

我有一个非常基本的循环

function getdatatableajax()
   {
        if($this->input->get('search_term')) { $search_term = $this->input->get('search_term'); } else { $search_term = false;}

       $this->load->library('datatables');
       $this->datatables
            ->select("sales.id as sid, sales.date as date, sales.reference_no as reference_no, sales.biller_name as biller_name, sales.customer_name as customer_name, sales.total_tax as total_tax, sales.total_tax2 as total_tax2, sales.total as total, internal_note as sintnote")
            ->from('sales')
            ->join(deliveries, 'sales.reference_no = deliveries.reference_no', 'left');
            $this->datatables->add_column("Actions", 
            "<center><a href='#' title='$2' class='tip' data-html='true'><i class='icon-folder-close'></i></a> <a href='#' onClick=\"MyWindow=window.open('index.php?module=sales&view=view_invoice&id=$1', 'MyWindow','toolbar=0,location=0,directories=0,status=0,menubar=yes,scrollbars=yes,resizable=yes,width=1000,height=600'); return false;\" title='".$this->lang->line("view_invoice")."' class='tip'><i class='icon-fullscreen'></i></a> 
            <a href='index.php?module=sales&view=add_delivery&id=$1' title='".$this->lang->line("add_delivery_order")."' class='tip'><i class='icon-road'></i></a>
            <a href='index.php?module=sales&view=pdf&id=$1' title='".$this->lang->line("download_pdf")."' class='tip'><i class='icon-file'></i></a> 
            <a href='index.php?module=sales&view=email_invoice&id=$1' title='".$this->lang->line("email_invoice")."' class='tip'><i class='icon-envelope'></i></a>
            </center>", "sid, internal_note")

        ->unset_column('sid')
        ->unset_column('internal_note');
       echo $this->datatables->generate();

   }

我希望第二天能够给我制作MM / DD / YYYY但是第一次迭代是第二天,但是它会跳过6个月。

作为一个新的Momemnt.js用户,我不确定我哪里出错了

enter image description here

1 个答案:

答案 0 :(得分:0)

问题出在循环内的语句中:

thisDate = moment(thisDate,'MM/DD/YYYY').add(1,'days').toDate('MM/DD/YYYY');

第一个错误是在第一个参数是moment对象时将格式字符串传递给Date构造函数。 As described here,只有当第一个参数是包含日期的字符串时才需要传递格式字符串:

thisDate = moment(thisDate).add(1,'days').toDate('MM/DD/YYYY');

add调用是正确的,但doDate调用不正确。函数toDate does not take in input a format string

thisDate = moment(thisDate).add(1,'days').toDate();

这里有完整的代码片段:

var thisDate = new Date(),
    checkcounter = 0;

console.log('Init:', thisDate);
while (checkcounter < 10) {
    console.log('Check counter:', checkcounter);
    thisDate = moment(thisDate).add(1, 'days').toDate();
    console.log('thisDate:', thisDate);
    checkcounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>