You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将日期时间格式化为01-Mar-2000 10:10:10 PM/AM?求一行优化代码

日期时间格式化为01-Mar-2000 10:10:10 AM/PM的一行代码实现

以下是主流编程语言的一行优化实现方案:

Python

利用datetime模块的strftime方法直接指定格式:

from datetime import datetime; print(datetime.now().strftime("%d-%b-%Y %I:%M:%S %p"))
  • %d: 两位数字的日期(01-31)
  • %b: 缩写月份(Jan-Dec)
  • %Y: 四位数字的年份
  • %I: 12小时制的小时(01-12)
  • %M: 两位数字的分钟(00-59)
  • %S: 两位数字的秒(00-59)
  • %p: 上午/下午标识(AM/PM)

JavaScript

使用原生Intl.DateTimeFormat配置格式,替换默认的逗号分隔符:

console.log(new Date().toLocaleString('en-US', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }).replace(/, /, ' '))

Java

借助Java 8+的java.time工具类实现:

System.out.println(java.time.format.DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a").format(java.time.LocalDateTime.now()));

内容的提问来源于stack exchange,提问作者R Gowtham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:05:30