如何将Date对象格式化为字符串?
当前回答
我使用以下方法。它很简单,工作正常。
var dtFormat = require('dtformat');
var today = new Date();
dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");
或者这个:
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
其他回答
我知道有人可能会说这是一个愚蠢的解决方案,但它确实做到了从日期字符串中删除不必要的信息。
yourDateObject生成:
2017年12月13日星期三20:40:40 GMT+0200(欧洲东部时间)
yourDateObject.toString().sslice(0,15);生产:
2017年12月13日星期三
new Date().toLocaleDateString()// "3/21/2018"
developer.mozilla.org上的更多文档
函数convert_month(i=0,option=“num”){//i=索引变量对象月=[{num:01,短:“Jan”,长:“Janer”},{num:02,短:“Feb”,长:“Februari”},{num:03,短:“Mar”,长:“March”},{num:04,短:“Apr”,长:“April”},{num:05,短:“May”,长:“May”},{num:06,短:“Jun”,长:“Juni”},{num:07,短:“Jul”,长:“July”},{num:08,短:“Aug”,长:“August”},{num:09,短:“Sep”,长:“Sept”},{num:10,短:“Oct”,长:“Octo”},{num:11,短:“Nov”,长:“十一月”},{num:12,短:“Dec”,长:“十二月”}];返回object_months[i][option];}var d=新日期();// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascriptvar num=`${d.getDate()}-${convert_month(d.getMonth())}--${d.getFullYear()}';var short=`${d.getDate()}-${convert_month(d.getMonth(),“short”)}-${d.getFullYear()}`;var long=`${d.getDate()}-${convert_month(d.getMonth(),“long”)}-${d.getFullYear()}`;document.querySelector(“#num”).innerHTML=num;document.querySelector(“#short”).innerHTML=短;document.querySelector(“#long”).innerHTML=long;<p>数字:<span id=“num”></span>(默认值)</p><p>短:<span id=“Short”></span></p><p>长:<span id=“Long”></span></p>
字体版本
可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。
原型函数
interface Date {
format(formatString: string): string;
}
Date.prototype.format = function (formatString: string): string {
return Object.entries({
YYYY: this.getFullYear(),
YY: this.getFullYear().toString().substring(2),
yyyy: this.getFullYear(),
yy: this.getFullYear().toString().substring(2),
MMMM: this.toLocaleString('default', { month: 'long' }),
MMM: this.toLocaleString('default', { month: 'short' }),
MM: (this.getMonth() + 1).toString().padStart(2, '0'),
M: this.getMonth() + 1,
DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
DDD: this.toLocaleDateString('default', { weekday: 'short' }),
DD: this.getDate().toString().padStart(2, '0'),
D: this.getDate(),
dddd: this.toLocaleDateString('default', { weekday: 'long' }),
ddd: this.toLocaleDateString('default', { weekday: 'short' }),
dd: this.getDate().toString().padStart(2, '0'),
d: this.getDate(),
HH: this.getHours().toString().padStart(2, '0'), // military
H: this.getHours().toString(), // military
hh: (this.getHours() % 12).toString().padStart(2, '0'),
h: (this.getHours() % 12).toString(),
mm: this.getMinutes().toString().padStart(2, '0'),
m: this.getMinutes(),
SS: this.getSeconds().toString().padStart(2, '0'),
S: this.getSeconds(),
ss: this.getSeconds().toString().padStart(2, '0'),
s: this.getSeconds(),
TTT: this.getMilliseconds().toString().padStart(3, '0'),
ttt: this.getMilliseconds().toString().padStart(3, '0'),
AMPM: this.getHours() < 13 ? 'AM' : 'PM',
ampm: this.getHours() < 13 ? 'am' : 'pm',
}).reduce((acc, entry) => {
return acc.replace(entry[0], entry[1].toString())
}, formatString)
}
Javascript版本
同样,只需删除接口,以及冒号及其关联冒号之后的类型名称。
demo
function unitTest() {
var d: Date = new Date()
console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}
unitTest()
只需执行以下操作:-
let date = new Date().toLocaleDateString('en-us',{day: 'numeric'})
let month = new Date().toLocaleDateString('en-us',{month: 'long'})
let year = new Date().toLocaleDateString('en-us',{year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA