简体   繁体   English

将日期字符串转换为 Postgres 时间戳时区格式

[英]Convert date string to Postgres timestamp timezones format

I have the following date:我有以下日期:

25-JAN-18 01.31.02 AM +00:00

and am trying to convert into a Postgres compatible timestamp with time zone format.并且正在尝试将timestamp with time zone格式转换为 Postgres 兼容的timestamp with time zone

I am trying the following code to convert into the compatible format:我正在尝试将以下代码转换为兼容格式:

document.getElementById("parsedDate3").innerHTML = moment("25-JAN-18 01.31.02.923526 AM +00:00 ", "d-MMM-YY hh.mm.ss A Z");

But I am getting the output as但我得到的输出为

Mon Jan 01 2018 02:31:02 GMT+0100

Can anyone please help me with this.任何人都可以帮我解决这个问题。

You are using lower-case d which is for the day of the week, 0 (Sunday) through 6 (Saturday).您使用的是小写的d ,它代表一周中的哪一天,0(星期日)到 6(星期六)。

Use upper-case D instead, which is for the day of the month.使用大写D代替,它代表一个月中的某一天。

Note that Moment's formatting tokens are slightly different than in other libraries and languages, so check the chart in the docs carefully.请注意,Moment 的格式标记与其他库和语言中的略有不同,因此请仔细检查文档中的图表。

Also:还:

  • In your code you have 6 extra digits following the seconds.在您的代码中,秒后有 6 个额外的数字。 If you need to account for those, use SSSSSS .如果您需要考虑这些,请使用SSSSSS Otherwise they are ignored.否则它们将被忽略。

  • You shouldn't assign a Moment object directly to an HTML element's innerHTML property.您不应将 Moment 对象直接分配给 HTML 元素的innerHTML属性。 Instead, call the .format() function on the Moment object first to generate a string.相反,首先在 Moment 对象上调用.format()函数来生成一个字符串。 You can optionally pass an argument to this function, to control the output format.您可以选择将参数传递给此函数,以控制输出格式。

You can simply do it in PostgreSQL:你可以简单地在 PostgreSQL 中做到:

SELECT to_timestamp('25-JAN-18 01.31.02.923526 AM +00:00', 'DD-MON-YY HH.MI.SS.US AM TZH:TZM');

         to_timestamp      
-------------------------------
 2018-01-25 02:31:02.923526+01
(1 row)

This will work for PostgreSQL v11 or better.这适用于 PostgreSQL v11 或更高版本。

Earlier versions of to_timestamp cannot parse the time zone information yet.早期版本的to_timestamp还不能解析时区信息。

If you need it to work on 9.6, and you know that the time zone is always going to be +00:00 , you could simple omit the TZH:TZM in the format string.如果你需要它在 9.6 上工作,并且你知道时区总是+00:00 ,你可以简单地省略格式字符串中的TZH:TZM

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

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