使用Moment.js處理時(shí)間戳轉(zhuǎn)化為時(shí)間年月

Moment.js 是一個(gè) JavaScript 日期處理類庫(處理時(shí)間格式化的npm包),用于解析、檢驗(yàn)、操作、以及顯示日期,在新公司的項(xiàng)目中,大量使用Moment來處理時(shí)間日期,非常方便好用。

Moment.js 中文網(wǎng):
http://momentjs.cn/

優(yōu)點(diǎn):

不依賴任何第三方庫
支持字符串、Date、時(shí)間戳以及數(shù)組等格式
可以同時(shí)在瀏覽器和node環(huán)境中使用
前后端通用,文檔也很詳細(xì)
方便了日常開發(fā)中對時(shí)間的操作,提高了開發(fā)效率

使用步驟

1:在項(xiàng)目里面安裝Moment
cnpm install moment --save
2:在要使用的組件里面引入
import moment from 'moment'; 
3:時(shí)間戳如下
{
  "users": [
    {
        "startTime":"1572502840091",
        "endTime":"1572512489920"
       
    }, {
     
      "startTime":"1572512489920",
      "endTime":"1572513935374"
    }
]
}
4:代碼

這里把時(shí)間戳做成了mock數(shù)據(jù),使用axios對數(shù)據(jù)接口進(jìn)行請求,請求完成之后渲染在前端界面,如果有不理解的地方可以查看專題從零開始學(xué)react系列教程。

import React from 'react';
import axios from 'axios';
import moment from 'moment';
class Time extends React.Component {
  //構(gòu)造函數(shù)
  constructor() {
    super();
    //react定義數(shù)據(jù)
    this.state = {
      list: []
    }
  }
  //請求接口的方法
  getData = () => {
    var api = 'http://localhost:3004/users';
    axios.get(api)
      .then((response) => {
        // handle success
        console.log(response.data);
        //用到this需要注意指向,箭頭函數(shù)
        this.setState({
          list: response.data
        })
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      });
  }
  render() {
    return (
      <div>
        <h2>時(shí)間戳轉(zhuǎn)化為時(shí)間</h2>
        <button onClick={this.getData}>獲取時(shí)間</button>
        <ul>
          {
            this.state.list.map((value, key) => {
              let start = moment(parseInt(value.startTime)).format('YYYY/MM/DD hh:mm:ss');
              let end = moment(parseInt(value.endTime)).format('YYYY/MM/DD hh:mm:ss');
              return (

                <li key={key}>
                  <span>開始時(shí)間:{start}</span>
                  <span>結(jié)束時(shí)間:{end}</span>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}
export default Time;

5:效果

代碼運(yùn)行如下,獲取到了時(shí)間年月日了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容