[Javascript] Natively Format JavaScript Dates and Times

The ability to natively format dates and times using the browser is impressive. You may find yourself not needed to grab libraries such as moment.js or date-fns when doing simple formatting and better yet, the browser support is surprisingly good!

复制代码
const date = new Date();

console.log(date.toLocaleDateString());
console.log(date.toLocaleDateString("en-US"));
console.log(date.toLocaleDateString("fr-FR"));
const dateOptions = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};
console.log(date.toLocaleDateString("en-US", dateOptions));
console.log(
  date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric"
  })
);
console.log(
  date.toLocaleDateString("fr-FR", {
    month: "long"
  })
);
console.log(date.toLocaleTimeString());
console.log(date.toLocaleTimeString("en-US"));
console.log(date.toLocaleTimeString("de-DE"));
const timeOptions = {
  hour12: true,
  hour: "numeric",
  minute: "2-digit",
  second: "2-digit",
  timeZone: "America/Los_Angeles"
};
console.log(date.toLocaleTimeString("en-US", timeOptions));
console.log(
  date.toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit"
  })
);
console.log(
  date.toLocaleTimeString("en-US", {
    hour12: false
  })
);
console.log(
  date.toLocaleString("en-US", {
    ...dateOptions,
    ...timeOptions
  })
);
const dateTimeFormat = new Intl.DateTimeFormat("en-US", {
  ...dateOptions,
  ...timeOptions
});
console.log(dateTimeFormat.format(date));
const anotherDate = new Date("2000-12-25T12:34:56.789Z");
console.log(dateTimeFormat.format(anotherDate));
复制代码

 

posted @   Zhentiw  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-08-06 [Functional Programming] liftA2 and converge
2019-08-06 [Javascript] Convert a forEach method to generator
2019-08-06 [Flutter] Platform Checking
2019-08-06 [Flutter] Stateless widget and Stateful widget
2018-08-06 [Vue] Props Validations
2018-08-06 [JavaEE] Create API documents with Swagger
2017-08-06 [D3] Basic Interactivity with D3 v4
点击右上角即可分享
微信分享提示