js——date,moment和string類型的轉換

最近在使用antd的datepicker組件時,又遇到了時間戳的轉換,正好一起總結下。

開發中時間元素經常出現,我們往往需要將時間轉換爲我們需要的格式來使用。比如,我在使用datepicker控件時,需要將時間作爲參數傳遞給後臺,同時在頁面上展示出來。

關於moment的詳細信息,可以參考http://momentjs.cn/

    let time = moment();

    console.log(time);

    console.log(typeof time.format('YYYY/MM/DD') + ' ' + time.format('YYYY/MM/DD'));
    
    console.log(typeof time.valueOf() + ' ' + time.valueOf());

    console.log(typeof Date.parse(time) + ' ' + Date.parse(time));

 

 

可以看到,format可以將moment轉換爲指定格式的string類型,Date.parse和valueOf可以將moment轉換爲Number類型。

 

    let time1 = new Date(1577808000000);
    let time2 = new Date('2020/1/1');

    console.log(time2);

    console.log(Date.parse(time1));

    console.log(time2.valueOf());

    console.log(moment(time1));

    console.log(moment(time1).format('YYYY/MM/DD'));

可以看到,我們可以直接將string,number作爲參數,轉換成date。轉換成moment也是直接作爲參數傳入即可。

此外,我們可以通過Date.parse和valueOf將Date數據轉換爲Number,指定格式的string則可以通過——先轉換爲moment再用format轉換爲string的方式。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章