[英]How to convert a date as a string to "dd/mm/yyyy"?
We are using Moment.js to format the date.我们使用 Moment.js 来格式化日期。
How can I format such a date:我怎样才能格式化这样的日期:
const createdAt = 'Mar 29 2019 5:02PM'
to a dd/mm/yyyy
format?到
dd/mm/yyyy
格式?
I already tried with:我已经尝试过:
moment(createdAt).toDate();
moment(createdAt).format('DD/MM/YYYY');
but I got Invalid date
for both.但我得到了两者的
Invalid date
。
You'll need to specify the format because that is not a known date format, something like this:您需要指定格式,因为这不是已知的日期格式,如下所示:
const result = moment('Mar 29 2019 5:02PM', "MMM DD YYYY hh:mmA").format('DD/MM/YYYY'); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
You don't necessarily need moment
to do that, especially if you need to tell it how to parse the string.你不一定需要
moment
来做这件事,特别是如果你需要告诉它如何解析字符串。 For such a simply task, perhaps you could do it yourself?这么简单的任务,或许你可以自己做?
const convert = date_str => date_str.toLowerCase().replace(/^(\\w+) (\\d+) (\\d+) .+$/, (full_match, month, day, year) => { const month_num = month === 'jan' ? '01' : month === 'feb' ? '02' : month === 'mar' ? '03' : month === 'apr' ? '04' : month === 'may' ? '05' : month === 'jun' ? '06' : month === 'jul' ? '07' : month === 'aug' ? '08' : month === 'sep' ? '09' : month === 'oct' ? '10' : month === 'nov' ? '11' : '12'; return `${day}/${month_num}/${year}` }); console.log(convert('Mar 29 2019 5:02PM'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.