2

How do I convert a 7-digit Julian Date (2016092) to a regular Calendar date (MM-DD-YYYY)?

I was thinking of taking the last three digits and converting it to a regular date then appending the first four digits as the year but I'd have to consider leap years.

Expected output: 04-01-2016

My current (SQL) code which solves the problem is

DECLARE @dt char(7) 
SET @dt = 2016092 

SELECT DATEADD(dd, CAST(RIGHT(@dt, 3) AS int) - 1, CAST(LEFT(@dt, 4) AS datetime))

How can I implement it on C#?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • As far as I can see `04-01-2016` equals to `2457391.50000 JD` (not `2016092`), https://en.wikipedia.org/wiki/Julian_day online calc https://www.aavso.org/jd-calculator; – Dmitry Bychenko Nov 16 '17 at 10:27
  • Hi, I saw this code somewhere in here (sorry if I can't provide a link) : `DECLARE @dt char(7) SET @dt = 2016092 SELECT DATEADD(dd, CAST(RIGHT(@dt, 3) AS int) - 1, CAST(LEFT(@dt, 4) AS datetime))` This is basically for SQL but it outputs the one I have provided. – Daniel Valle Nov 16 '17 at 10:39

1 Answers1

4

You don't have any kind of Julian Day (Date) format which is

https://en.wikipedia.org/wiki/Julian_day

But a kind of custom format which can be reconstructed from the sql provided:

  year * 1000 + days from 1st Jan + 1

So 2016092 means year 2016 and 092 - 1 = 91st day from the 1st of Jan (1st of Apr)

Implementation:

int source = 2016092;
DateTime result = new DateTime(source / 1000, 1, 1).AddDays(source % 1000 - 1);

Console.WriteLine($"{result:MM-dd-yyyy}");

Outcome:

04-01-2016
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215