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的方式。

 

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