How to convert moment date to a string and remove the moment object

后端 未结 2 1696
北海茫月
北海茫月 2021-02-07 05:19

I have a React Web App and a React Native Mobile App. When I pass a moment date object from my react web app to my backend, it gets converted to a string somehow and it works wi

相关标签:
2条回答
  • 2021-02-07 05:51

    Use moment().format() to create a formatted string from the date.

    console.log(moment().format())
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

    But if you're using version 2.1.0+ (link), toString should work:

    console.log(moment().toString())
    console.log(typeof moment().toString())
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

    0 讨论(0)
  • 2021-02-07 06:12

    You're trying to call methods that only exist on a javascript Date object. In order to call those methods you'd need to first convert the Moment object into a plain Date object. You can use the .toDate() method on the Moment object to do this.

    var plainDate = moment().toDate();
    console.log(plainDate.toUTCString());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

    However, a more direct way of converting a Moment object to a string is to use the .format() method, which will output as "ISO 8601" standard that looks like 2014-09-08T08:02:17-05:00.

    console.log( moment().format() );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

    0 讨论(0)
提交回复
热议问题