[英]Check if date has already been parsed with moment
I am passing down a date string which needs to be parsed appropriately with moment
.我正在传递一个需要用moment
适当解析的日期字符串。 The problem is in some circumstances it is getting parsed twice, which causes it to become undefined
.问题是在某些情况下它会被解析两次,这会导致它变成undefined
。
this is what the code currently looks like:这是代码目前的样子:
moment.tz(dt, 'MMMM D, YYYY', timezone).toDate()
When I parse it the second time, I get:当我第二次解析它时,我得到:
moment.invalid(/* 2018-09-21T05:00:00.000Z */) moment.invalid(/* 2018-09-21T05:00:00.000Z */)
Which causes when I do toDate()
to become undefined
.这导致当我执行toDate()
时变为undefined
。
while the first time I will get exactly what I expect:而第一次我会得到我所期望的:
'2019-02-01T05:00:00.000Z' '2019-02-01T05:00:00.000Z'
Before doing any of this I would like to check if it already if in the format I expect it to be.在做任何这些之前,我想检查它是否已经是我期望的格式。 How do I do this?我该怎么做呢?
You could potentially use the isValid() method to check if the parsing worked before calling toDate()
.您可以潜在地使用isValid()方法在调用toDate()
之前检查解析是否有效。 Demo:演示:
var timezone = "America/Los_Angeles"; var dt = 'Sept 21, 2018'; var m = moment.tz(dt, 'MMMM D, YYYY', timezone); var converted = m.toDate().toString(); console.log(converted); var x = moment.tz(converted, 'MMMM D, YYYY', timezone); console.log(x.isValid()); //if parsing worked, use the new value if (x.isValid()) { console.log(x.toDate()); } // if not, assume it's already the correct format and just use that else { console.log(converted); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.