Dayjs:无法将自定义的24小时时间设置为12小时


import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
dayjs.extend(customParseFormat);

当执行类似这样的"dayjs().format('18:00', "hh:mm A");"时,它不会转换为12小时计时。。。。返回18:00

如何使用dayjs转换输出,如:

08:00 -> 08:00 AM
18:00 -> 06:00 PM

我接受了接受的答案,并为我的用例简化了一点。这几乎是相同的用例。

如果日期无关紧要,而你只是想转换时间,那么这应该就是你所需要的。

const globalTime = "14:00";
const twelveHourTime = dayjs('1/1/1 ' + globalTime).format('hh:mm a')
// twelveHourTime = "02:00 pm"

由于dayjs需要一个完整的日期来格式化它,但唯一的输出是时间,因此日期是不相关的,可以是任何东西。比如,";1/1/1";

要做到这一点,不能只设置"18:00",必须指定一个日期。

var now = new dayjs().startOf('day')
var newDate = now.add('18','hour').add('10','minutes')
var newDatezerominutes = now.add('18','hour').add('00','minutes')
var formatted = dayjs(newDate).format('hh:mm a')
var formattedzero = dayjs(newDatezerominutes).format('hh:mm a')
console.log(`To see differences ${formatted}`) 
console.log(`Your case ${formattedzero}`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.34/dayjs.min.js"></script>

最新更新