使用.map创建表格时格式化日期字符串

时间:2018-02-22 22:10:43

标签: javascript reactjs jsx

我使用.ref和React来创建基于coupons对象的表。尝试将日期字符串格式化为“mm / dd / yyyy”格式。 coupon.starts_at通常为coupon.starts_at = "2013-08-03T02:00:00Z"

我想我在错误的地方宣布这个功能..我在组织这个时哪里出错了?

import React from 'react'

export default ({ coupons, edit }) =>

<div className="row no-gutters">
    <div className="col-3 Col TitleCol">
      <h3 className="sub-heading">Existing Coupons</h3>
    </div>
    <div className="col-9 Col ContentCol">
      <table className="settings-table stack">
        <thead>
          <tr>
              <th>Code</th>
              <th>Discount</th>
              <th>Description</th>
              <th>Start Date</th>
              <th>Expiration Date</th>
              <th></th>

         </tr>
        </thead>
        <tbody>
        {
            coupons.map(coupon =>
                <tr key={coupon.id}>
                    <td>{coupon.code}</td>
                    <td>{coupon.discount}</td>
                    <td>{coupon.description}</td>
                    <td>{formatDate(coupon.starts_at)}</td>
                    <td>{coupon.expires_at}</td>
                    <td className="remove nowrap">
                      <span className="ahref" onClick={(event) => {event.preventDefault(); edit(coupon.id)}}>Edit</span>
                    </td>
                </tr>
            )
        }
        </tbody>
      </table>
    </div>
  </div>
  {
    let date = new Date(coupon.starts_at);
    function formatDate(date){
      let year = date.getFullYear();
      let month = date.getMonth()+1;
      let day = date.getDate()+1;
      if (day < 10) {
        day = '0' + day;
      }
      if (month < 10) {
        month = '0' + month;
      }
      date = month+'/'+day+'/'+year
      return date;
    }
  }

2 个答案:

答案 0 :(得分:0)

只需使用新的日期(日期)将字符串包装到Date对象,它应该没问题。

{
    let date = new Date(coupon.starts_at);
    function formatDate(date){
      let year = date.getFullYear();
      let month = date.getMonth()+1;
      let day = date.getDate()+1;
      if (day < 10) {
        day = '0' + day;
      }
      if (month < 10) {
        month = '0' + month;
      }
      date = month+'/'+day+'/'+year
      return date;
    }

答案 1 :(得分:0)

请试试这个。 :)它在我身边运行得非常好。

&#13;
&#13;
let date = new Date('2013-08-03T02:00:00Z');
    function formatDate(date){
      let year = date.getFullYear();
      let month = date.getMonth()+1;
      let day = date.getDate()+1;
      if (day < 10) {
        day = '0' + day;
      }
      if (month < 10) {
        month = '0' + month;
      }
      return month+'/'+day+'/'+year;
      }
      
 console.log(formatDate(date));
&#13;
&#13;
&#13;