Javascript 如何使用 moment js 从日期时间字符串中获取 am pm

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44971954/
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 02:49:51  来源:igfitidea点击:

How to get am pm from the date time string using moment js

javascriptmomentjs

提问by User 101

I have a string as Mon 03-Jul-2017, 11:00 AM/PMand I have to convert this into a string like 11:00 AM/PMusing moment js.

我有一个字符串Mon 03-Jul-2017, 11:00 AM/PM,我必须像11:00 AM/PM使用 moment js一样将其转换为字符串。

The problem here is that I am unable to get AMor PMfrom the date time string.

这里的问题是我无法获取AMPM来自日期时间字符串。

I am doing this:

我正在这样做:

moment(Mon 03-Jul-2017, 11:00 AM, 'dd-mm-yyyy hh:mm').format('hh:mm A')

and it is working fine as I am getting 11:00 AMbut if the string has PMin it it is still giving AMin the output.

它在我得到的时候工作正常,11:00 AM但如果字符串中有PM它,它仍然AM在输出中给出。

like this moment(Mon 03-Jul-2017, 11:00 PM, 'dd-mm-yyyy hh:mm').format('hh:mm A')is also giving 11:00 AMin output instead of 11:00 PM

像这样moment(Mon 03-Jul-2017, 11:00 PM, 'dd-mm-yyyy hh:mm').format('hh:mm A')也给出11:00 AM了输出而不是11:00 PM

回答by VincenzoC

You are using the wrong format tokens when parsing your input. You should use dddfor an abbreviation of the name of day of the week, DDfor day of the month, MMMfor an abbreviation of the month's name, YYYYfor the year, hhfor the 1-12hour, mmfor minutes and Afor AM/PM. See moment(String, String)docs.

您在解析输入时使用了错误的格式标记。您应该使用ddd的星期几的名称的缩写, DD该月的一天,MMM该月的名称的缩写,YYYY在今年,hh对于1-12小时,mm为分钟AAM/PM。请参阅moment(String, String)文档。

Here is a working live sample:

这是一个有效的实时示例:

console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

回答by Deepu Reghunath

you will get the time without specifying the date format. convert the string to date using Dateobject

您将在不指定日期格式的情况下获得时间。使用Date对象将字符串转换为日期

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');

working solution:

工作解决方案:

var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');
console.log(moment(myDate).format('HH:mm')); // 24 hour format 
console.log(moment(myDate).format('hh:mm'));
console.log(moment(myDate).format('hh:mm A'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>