简体   繁体   English

使用javascript将SQL日期数字转换为日期

[英]Convert SQL date number into date using javascript

Gabriele Petrioli please read my question before you close it. Gabriele Petrioli 请在关闭之前阅读我的问题。

my reports in SQL are daily, and INT as Date is perfect, two years ago I test Azure CosmosDB and I was able to convert by using JavaScript I did it by using UDF I just needed now for a project and bad luck, can't believe so many people are involved to downplay questions and administrating without programming skills and "managing", I will do it again I will not give up but I need the code today.我在 SQL 中的报告是每天的,并且 INT 作为日期是完美的,两年前我测试了 Azure CosmosDB 并且我能够使用 JavaScript 进行转换我使用 UDF 做到了我现在只需要一个项目并且运气不好,不能相信有这么多人在没有编程技能和“管理”的情况下淡化问题和管理,我会再做一次,我不会放弃,但我今天需要代码。 I will post the solution if the managers did not close my question again.如果经理没有再次关闭我的问题,我会发布解决方案。

here the original question:这里是原始问题:

I need to convert INT date produced by SQL into a Date using javascript.我需要使用 javascript 将 SQL 生成的 INT 日期转换为日期。

I know this is possible I did it before I have a terrible day today and the time is clicking.我知道这是可能的,我是在今天糟糕的一天之前做到的,而且时间快到了。

Here is the process: I convert the date to INT using SQL这是过程:我使用 SQL 将日期转换为 INT

select 'cast(getdate() as  int)'
select cast(getdate()  as  int)
-- today 43811

I need to bring it back using Javascript.我需要使用 Javascript 把它带回来。 No Jquery or else.没有 Jquery 或其他。

--more exaples
select 'cast(40702 as  smalldatetime)'
select cast(40702 as  smalldatetime)
--output 2011-06-10 00:00:00


select 'cast(getdate() as  float)'
select cast(getdate()  as  float)
-- output 43810.6597960262

Again I need to use JavaScript我再次需要使用 JavaScript
convert2date(40702) --> 2011-06-10转换日期(40702)--> 2011-06-10

convert2date(43811) --> 2019-12-14 convert2date(43811) --> 2019-12-14

What you have is a day count from 1900-01-01 and you need to add the given days.您拥有的是从 1900-01-01 开始的天数,您需要添加给定的天数。

 function convert2date(days) { const isLeapYear = year => (!(year % 4) && !!(year % 100)) || !(year % 400), daysInMonth = (month, year) => [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] + isLeapYear(year); var date = [1900, 1, 1], y = isLeapYear(date[0]) + 365, d; while (days >= y) { date[0]++; days -= y; y = isLeapYear(date[0]) + 365; } d = daysInMonth(date[1], date[0]); while (days >= d) { date[1]++; days -= d; d = daysInMonth(date[1], date[0]); } date[2] += days; return date.map((v, i) => v.toString().padStart(i ? 2 : 4, 0)).join('-'); } console.log(convert2date(40702)); // 2011-06-10 console.log(convert2date(43811)); // 2019-12-14

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

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