如何将Date对象格式化为字符串?
当前回答
在我的情况下,我已将日期表“2022年7月1日”格式化为“2022-07-01”
常量格式日期=日期=>{const d=新日期(日期)let month=(d.getMonth()+1).toString()let day=d.getDate().toString()const year=d.getFullYear()如果(月长度<2){月=“0”+月}如果(日长度<2){天=“0”+天}return[年,月,日]。join('-')}console.log(格式日期('01/07/2022'))
其他回答
new Date().toLocaleDateString()// "3/21/2018"
developer.mozilla.org上的更多文档
使用ECMAScript Edition 6(ES6/ES2015)字符串模板:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
如果需要更改分隔符:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat
我想你可以使用非标准的Date方法来LocaleFormat(formatString)
formatString:与C中strftime()函数期望的格式相同的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
到区域设置格式斯特夫蒂姆
一行中请求的格式-没有库和Date方法,只有正则表达式:
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有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