如何使用时刻js从日期时间字符串获取pm

Use*_*101 41 javascript momentjs

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

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

我这样做:

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

并且它正常工作,11:00 AM但如果字符串中有PM它仍然AM在输出中给出.

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

Vin*_*zoC 84

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

这是一个有效的实时样本:

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') );
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


Pus*_*pak 15

前面提到的答案很完美。但也有一些其他方法

console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('LT') );
Run Code Online (Sandbox Code Playgroud)

晚上 11:00

moment().format('LT');   // 5:50 PM
moment().format('LTS');  // 5:50:35 PM
moment().format('L');    // 18/02/2022
moment().format('l');    // 18/2/2022
moment().format('LL');   // 18 February 2022
moment().format('ll');   // 18 Feb 2022
moment().format('LLL');  // 18 February 2022 5:50 PM
moment().format('lll');  // 18 Feb 2022 5:50 PM
moment().format('LLLL'); // Friday, 18 February 2022 5:50 PM
moment().format('llll');
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请访问https://momentjs.com/


Dee*_*ath 9

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

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
Run Code Online (Sandbox Code Playgroud)

工作解决方案:

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
Run Code Online (Sandbox Code Playgroud)
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'));
Run Code Online (Sandbox Code Playgroud)