【问题标题】:Dayjs: unable to format custom 24hr time to 12hrDayjs:无法将自定义 24 小时时间格式化为 12 小时
【发布时间】:2020-12-15 13:27:26
【问题描述】:
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

【问题讨论】:

    标签: javascript time-format dayjs


    【解决方案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>

    【讨论】:

      【解决方案2】:

      我接受了已接受的答案,并针对我的用例对其进行了一些简化。这几乎是相同的用例。

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 2011-11-17
        • 2013-07-14
        相关资源
        最近更新 更多