Javascript 如何将时刻日期转换为字符串并删除时刻对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45809080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:13:37  来源:igfitidea点击:

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

javascriptreactjsreact-nativemomentjs

提问by Kelvin

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 with my backend.

我有一个 React Web 应用程序和一个 React Native 移动应用程序。当我将一个时刻日期对象从我的 React Web 应用程序传递到我的后端时,它会以某种方式转换为一个字符串,并且它可以与我的后端一起使用。

When I do it with my react native mobile app, it passes the date as a moment object and it doesn't get converted to a string and it doesn't work.

当我使用我的本机移动应用程序执行此操作时,它将日期作为时刻对象传递,并且不会转换为字符串并且不起作用。

Is there a way to convert the moment object into a plain string like

有没有办法将时刻对象转换为普通字符串,如

"Tue May 05 2015 23:59:59 GMT+0800 (HKT)"

I tried toString() and toUTCString() and it doesn't work. Thanks.

我试过 toString() 和 toUTCString() 但它不起作用。谢谢。

回答by kevguy

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

用于moment().format()从日期创建格式化字符串。

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), toStringshould work:

但是,如果您使用的是 2.1.0+ 版(链接),则toString应该可以:

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>

回答by Soviut

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

您正在尝试调用仅存在于 javascriptDate对象上的方法。为了调用这些方法,您需要首先将Moment对象转换为普通Date对象。您可以使用.toDate()Moment 对象上的方法来执行此操作。

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.

但是,将 Moment 对象转换为字符串的更直接方法是使用.format()方法,该方法将输出为“ISO 8601”标准,类似于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>