简体   繁体   English

如何在JavaScript中将没有时区的PostgreSQL时间转换为日期?

[英]How to convert PostgreSQL time without time zone to date in JavaScript?

I have a REST API endpoint that's using PostgreSQL that I'm querying against and one of the fields is a time without time zone . 我有一个REST API端点,它正在使用要查询的PostgreSQL,并且其中一个字段是time without time zone The endpoint returns the field as a human readable string like so 20:33:32.221397 . 端点将字段返回为人类可读的字符串,例如20:33:32.221397

I'd like to convert this on the front-end to another string like October 10, 2018 23:16 using JavaScript but the Date() object does not support this format. 我想使用JavaScript在前端将其转换为另一个字符串,如October 10, 2018 23:16Date()对象不支持此格式。

I tried moment.js and it throws an exception saying the format doesn't comply with RFC format. 我尝试了moment.js,它抛出了一个异常,说格式不符合RFC格式。

If it comes down to it, I'd like to just use regular expressions and extract the parts, convert it to milliseconds then use the Date() object but I'm not sure how to account for the floating point part as I'm sure it's of great significance. 如果涉及到这一点,我只想使用正则表达式并提取各部分,将其转换为毫秒,然后使用Date()对象,但是我不确定如何考虑浮点部分确保它具有重要意义。

Even the 7 parameter new Date() constructor expects the 2nd argument to be a month index, which I do not know. 甚至7个参数的new Date()构造函数都期望第二个参数是一个月索引,我不知道。

So, a JS library will do or I'd like to know the math on how to convert those parts into a timestamp. 因此,一个JS库可以或我想知道有关如何将这些部分转换成时间戳的数学方法。 The rest is trivial. 其余的都是微不足道的。 Thanks in advance. 提前致谢。

There is actually no straight way to parse more than 3 digits for SSS in time. 实际上,没有直接的方法可以为SSS及时解析多于3位的数字。 For your reference, there was an issue open with moment here 供大家参考,有一个问题与时刻打开这里

Do you need something like this? 你需要这样的东西吗?

function convertTime(apiTime) {
  var chunked = apiTime.split(":");

  var date = new Date();
  date.setHours(chunked[0]);
  date.setMinutes(chunked[1]);

  return moment(date).format('MMMM DD, YYYY H:mm');
}

convertTime("20:33:32.221397") // October 10, 2018 20:33

Here is a sandbox: https://jsfiddle.net/hxmrs92q/3/ 这是一个沙箱: https : //jsfiddle.net/hxmrs92q/3/

Okay. 好的。 I was a fool. 我当时很傻。 I realized the TIME type does not carry date fields with it. 我意识到TIME类型不带有日期字段。 The PHP function that was formatting the time simply assumed the date part. 用于格式化时间的PHP函数只是假定了日期部分。 I have since changed my type to TIMESTAMP now. 此后,我现在将类型更改为TIMESTAMP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM