C# Convert Julian Date

Little code fragment to assist with conversion to and from Julian date format. On my project I had to implement this within a BizTalk map via an inline C# scripting functoid.

        public static long ToJulian(DateTime dateTime)
        {
            int day = dateTime.Day;
            int month = dateTime.Month;
            int year = dateTime.Year;

            if (month < 3)
            {
                month = month + 12;
                year = year - 1;
            }

            return day + (153 * month - 457) / 5 + 365 * year + (year / 4) - (year / 100) + (year / 400) + 1721119;
        } 

        public static string FromJulian(long julianDate, string format) 
        { 
            long L = julianDate + 68569; 
            long N = (long) ((4*L)/146097); 
            L = L - ((long)((146097 * N + 3)/4) ); 
            long I = (long) ((4000 *(L + 1)/1461001)) ; 
            L = L - (long)((1461*I)/4) + 31;  
            long J = (long)((80*L)/2447);  
            int Day = (int)(L - (long)((2447*J)/80)); 
            L=(long)(J/11) ; 
            int Month = (int)(J + 2 - 12*L); 
            int Year = (int)(100*(N-49) + I + L) ; 
  
            // example format "dd/MM/yyyy"
            return new DateTime(Year,Month,Day).ToString(format); 
        }
Advertisements
This entry was posted in .NET, BizTalk Server. Bookmark the permalink.

3 Responses to C# Convert Julian Date

  1. Pingback: julian date convert | | CALENDAR SCHEDULECALENDAR SCHEDULE

  2. Henrik says:

    This turned out to be very usefull. Other conversion functions i tested did not work for julian to gregorian. Thanks!!

  3. JulianUser says:

    Thank you for this function. You would not believe how many other posted examples of ConvertFromJulian are nasty and horribly broken out there. Yours works, and the code is clean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s