3
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
4

2 回答 2

3

为此,您不能只设置“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>

于 2020-08-26T18:36:54.630 回答
3

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

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

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

由于您需要 dayjs 的完整日期来格式化它,但唯一的输出是时间,那么日期是无关紧要的,可以是任何东西。比如,“1/1/1”

于 2021-06-02T01:30:01.087 回答