在JavaScript中如何将日期转换为字符串

huangapple go评论60阅读模式
英文:

How to convert date to string in javascript

问题

I'm trying to convert javascript date to string but it's not working, i have a date like 2023-07-05 How to change it to 27 march 2023 please help me.

英文:

I'm trying to convert javascript date to string but it's not working, i have a date like 2023-07-05 How to change it to 27 march 2023 please help me

答案1

得分: 2

你可以使用 Date 对象及其函数来完成这个任务。

// 在线 JavaScript 编辑器,免费使用
// 使用 JS 在线编译器编写、编辑和运行您的 JavaScript 代码

// 使用原始日期创建一个新的 Date 对象
let date = new Date('2022-02-12'); // 在这里添加任何日期

let day = date.getDate();
let month = date.getMonth();
date.setMonth(month);

// 格式化日期为所需的字符串格式(DD Month YYYY)
let newDate = day + ' ' + date.toLocaleString('default', { month: 'long' }) + ' ' + date.getFullYear();
console.log(newDate);

英文:

You can make use of Date Object and it's functions to achieve this task.

// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler

// Create a new Date object with the original date
let date = new Date('2022-02-12'); // add any date here

let day = date.getDate();
let month = date.getMonth();
date.setMonth(month);

// Format the date as a string as required here (DD Month YYYY)
let newDate = day + ' ' + date.toLocaleString('default', { month: 'long' }) + ' ' + date.getFullYear();
console.log(newDate);

huangapple
  • 本文由 发表于 2023年5月7日 20:41:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定