如何在moment.js中将moment转换为自定义格式字符串

how to convert moment to custom format string in moment.js

本文关键字:moment 自定义 格式 字符串 转换 中将 js      更新时间:2023-09-26

我有一个瞬间对象,我想把它转换成格式为dd.mm.yy的字符串。用moment.js最好的方法是什么?

我尝试了toString函数,但它以Wed Mar 23 2016 00:00:00 GMT+0200的格式返回日期,手动转换它太费力了。

您可以使用moment format将moment对象转换为您喜欢的格式。在你的例子中:

var momObj = moment();
var timeToString = momObj.format('DD.MM.YY');
console.log(timeToString);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

moment.js lib对moment.js lib的引用,这是你唯一需要与时间一起工作的lib !

var momentObj = moment(); // will take now time and date as moment object
var formatDate = "DD.MM.YYYY HH:mm:ss"; // the string that represents desired format.
var result = momentObj.format(formatDate);
//result will be string "04.07.2016 12:25:12"