如何计算两个日期的持续时间?

发布于 2024-12-08 07:50:34 字数 638 浏览 1 评论 0原文

我有这个查询,这给了我一些问题,它看起来像这样:

UPDATE servicecontracts 
   SET planned_duration = (to_char(due_date) - to_char(start_date) + 1)
      ,actual_duration =''
      ,progress = NULL 
 WHERE servicecontractsid = '263'

经过一些研究,我设法弄清楚这个查询想要做什么,它只是试图通过减去到期日期来找到计划的持续时间和开始日期。为什么,这是试图通过减去字符串来做到这一点,我不知道。此外,to_char 函数需要第二个参数。

所以,无论如何,现在我需要找到 planned_duration,但我该怎么做呢?根据 Postgresql 文档,如果将 to_char 函数设置为返回文本,然后尝试使用显式转换将字符串转换为整数,则该函数没有返回整数的选项,就像 ::integer 一样,您会收到错误,因为整数中不能有冒号。
那么,有没有办法让 to_char 返回一个以某种方式表示日期的整数,然后将两者相减? 如果没有,我该怎么做才能实现这一点?

I have this query, that's been giving me some issues, it looks like this:

UPDATE servicecontracts 
   SET planned_duration = (to_char(due_date) - to_char(start_date) + 1)
      ,actual_duration =''
      ,progress = NULL 
 WHERE servicecontractsid = '263'

After some research, I managed to figure out what this query is trying to do, it' s just trying to find the planned duration, by subtracting the due date and the start date. Why, this is trying to do that by subtracting strings, I do not know. Also, the to_char function requires a second parameter.

So, anyway, now I need to find the planned_duration, but how do I do that. According to the Postgresql docs, the to_char function doesn't have an option to return an integer, if you set it to return text and then if you try to convert the string into an integer using explicit casts, like ::integer, you get an error because an integer can't have colons in there.
So, is there a way for to_char to return an integer that somehow represents the date, and then subtract the two?
If not, what should I do to carry this out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏花。依旧 2024-12-15 07:50:34

我在此处引用了精美手册

SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');

结果:982384720.12

但是对于计算间隔,有更简单的方法:

SELECT (due_date - start_date)

I quote from the fine manual here

SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');

Result: 982384720.12

But for computing intervals, there is simpler way:

SELECT (due_date - start_date)
霞映澄塘 2024-12-15 07:50:34

只需将两个 date 类型相减即可返回它们的天数差异。

SET planned_duration = (due_date - start_date)

不知道为什么使用 to_char ,除非我在这里遗漏了一些东西。

Just subtracting two date types from each other should return their difference in days.

SET planned_duration = (due_date - start_date)

Not sure why to_char is being used, unless I'm missing something here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文