Advertisement
kavallo

fnConvertJulianToDate

Mar 27th, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.65 KB | None | 0 0
  1. Create FUNCTION [dbo].[fnConvertJulianToDate]
  2. (
  3.  @JD DECIMAL(18,5)
  4. )
  5. RETURNS DATETIME
  6. AS
  7. BEGIN
  8.  
  9.  DECLARE @j INT
  10.  DECLARE @g INT
  11.  DECLARE @dg INT
  12.  DECLARE @c INT
  13.  DECLARE @dc INT
  14.  DECLARE @b INT
  15.  DECLARE @db INT
  16.  DECLARE @a2 INT
  17.  DECLARE @da INT
  18.  DECLARE @y2 INT
  19.  DECLARE @m2 INT
  20.  DECLARE @d INT
  21.  DECLARE @year INT
  22.  DECLARE @month INT
  23.  DECLARE @day INT
  24.  DECLARE @hr INT
  25.  DECLARE @min INT
  26.  DECLARE @sec INT
  27.  DECLARE @frac DECIMAL(18,5)
  28.  DECLARE @f DECIMAL(18,2)
  29.  DECLARE @finalDateTime DATETIME
  30.  
  31.  
  32.  SET @frac =  @JD - FLOOR(@JD) + 0.5
  33.  
  34.  IF(@frac >= 1.0)
  35.   BEGIN
  36.    SET @frac = @frac - 1.0
  37.    SET @JD = @JD + 1.0
  38.   END
  39.  
  40.  SET @j = FLOOR(@JD) + 32044
  41.  SET @g = @j / 146097
  42.  SET @dg = @j % 146097
  43.  SET @c = (@dg / 36524 + 1) * 3 / 4
  44.  SET @dc = @dg - @c * 36524
  45.  SET @b = @dc / 1461
  46.  SET @db = @dc % 1461
  47.  SET @a2 = (@db / 365 + 1) * 3 / 4
  48.  SET @da = @db - @a2 * 365
  49.  SET @y2 = @g * 400 + @c * 100 + @b * 4 + @a2
  50.  SET @m2 = (@da * 5 + 308) / 153 - 2
  51.  SET @d = @da - (@m2 + 4) * 153 / 5 + 122
  52.  SET @year = @y2 - 4800 + (@m2 + 2) / 12
  53.  SET @month = (@m2 + 2) % 12 + 1
  54.  SET @day = @d + 1.5
  55.  
  56.  
  57.  SET @hr  = FLOOR(@frac * 24.00)
  58.  SET @min  = FLOOR((@frac*24.00 - @hr)*60.00)
  59.  SET @f  = ((@frac*24.00 - @hr)*60.00 - @min)*60.00
  60.  SET @sec = FLOOR(@f)
  61.  SET @f = @f - @sec
  62.  
  63.  IF( @f > 0.5 )
  64.   BEGIN
  65.    SET @sec = @sec + 1
  66.   END
  67.  
  68.  SET @finalDateTime = CONVERT(VARCHAR(20), CAST(@month AS VARCHAR(2))
  69.     + '/'
  70.     + CAST(@day AS VARCHAR(2))
  71.     + '/'
  72.     + CAST(@year AS VARCHAR(4))
  73.     + ' '
  74.     + CAST(@hr AS VARCHAR(2))
  75.     + ':'
  76.     + CAST(@min AS VARCHAR(2))
  77.     + ':'
  78.     + CAST(@sec AS VARCHAR(2)))
  79.  
  80.  RETURN @finalDateTime
  81.  
  82. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement