使用 moment.js 在日期和时间之间添加空格 [英] Add space between date and time with moment.js

查看:69
本文介绍了使用 moment.js 在日期和时间之间添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以 ISO 格式从我的数据库中返回的日期时间.它们看起来像这样:2015-11-03T10:06:50.000Z.我正在使用 moment.js 来解析它,以便它更具可读性,结果如下所示:11-03-2015 10:06:50 AM.我只是想在日期和时间之间添加另一个空格,以便更容易阅读.有什么想法吗?

I have a datetimes coming back from my database in ISO format. They look like this: 2015-11-03T10:06:50.000Z. I am using moment.js to parse it out so that it's more readable and the result looks like this: 11-03-2015 10:06:50 AM. I simply want to add another space between the date and time so it's easier to read. Any thoughts?

我已经尝试在日期和时间之间添加另一个空格,但它似乎删除了除一个空格之外的所有空格.我也试过连字符和管道,但它们看起来并不像我想要的那样.

I've tried adding another space between the date and time in moment and it appears that it strips out all spaces except one. I've also tried hyphens and pipes but those don't really look the way I want.

rows.forEach(row => {
    // TODO find a way to put more blank space between date and time
    let formattedDateTime = moment.utc(row.DateTime).format(`MM-DD-YYYY hh:mm:ss A`)
    row.DateTime = formattedDateTime
    // console.log('formatted datetime', formattedDateTime)
  })

预期:在 moment.format 中的日期和时间之间添加空格会在客户端上反映这种方式.

Expected: adding spaces between the date and time in moment.format would reflect that way on the client.

实际:日期和时间之间只允许一个空格.删除所有其他空格.

Actual: only allowed one space between date and time. All other spaces are removed.

推荐答案

这不是 moment 或 vue 的问题,momentjs 会在您添加空格时添加它们(您可以通过调试 var 或使用控制台日志轻松检查)但默认情况下,您的浏览器会将多个空格折叠为一个空格.查看 white-space CSS 属性以了解更多信息.

It's not a problem of moment or vue, momentjs will add your white spaces as you add them (you can easily check by debugging your var or with console log) but your browser by default will collapse multiple spaces into only single space. Have a look at white-space CSS property to learn more.

另外,你不应该处理日期在你的 JS 中的显示方式,它应该在你的 CSS 中处理.所以我的建议是在你的 JS 代码中将日期和时间分成 2 个变量,并调整你的 HTML 模板和 CSS 以正确显示它们.

Also, you should not handle how the date will be displayed in your JS, it should be handled in your CSS. So my advice in your case is to separate date and time into 2 variables in your JS code and adapt your HTML template and CSS to display them properly.

通常在 HTML 代码中添加多个空格(甚至在 JS 代码中添加更多空格)并不是一个好方法,您应该使用 CSS 来实现.

Usually adding multiple spaces in your HTML code (and even more in your JS code) is not a good approach, you should instead achieve that with CSS.

这篇关于使用 moment.js 在日期和时间之间添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆