简体   繁体   English

Dayjs:无法将自定义 24 小时时间格式化为 12 小时

[英]Dayjs: unable to format custom 24hr time to 12hr

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

when executing something like this "dayjs().format('18:00', "hh:mm A");"当执行这样的"dayjs().format('18:00', "hh:mm A");" , it does not convert to 12 hr timing.... returns 18:00 , 它不会转换为 12 小时计时.... 返回 18:00

How do i get outputs converted using dayjs like:我如何使用 dayjs 转换输出,例如:

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

For doing that you can't just set the '18:00', you have to specify a date.为此,您不能只设置“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>

I took the accepted answer and simplified it a bit for my use case.我接受了接受的答案,并针对我的用例对其进行了一些简化。 Which is pretty much the same use case.这几乎是相同的用例。

If the date doesn't matter, and you are only trying to convert time -then this should be all you need.如果日期无关紧要,而您只是想转换时间 - 那么这应该就是您所需要的。

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

Since you need a full date for dayjs to format it, but the only output is the time, then the date is irrelevant and can just be anything.由于您需要 dayjs 的完整日期来对其进行格式化,但唯一的输出是时间,因此日期无关紧要,可以是任何内容。 Like, "1/1/1"像,“1/1/1”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM