RetroCoder RetroCoder - 1 year ago 655
C# Question

convert date yyyymmdd to yyJJJ or Julian Date

Need a formula in excel and c# to convert data in "yyyymmdd" format to julian date format "yyJJJ"? Where "JJJ" is the Julian date of day submitted. Is JJJ a number from 1 to 365 or 999 or 366? I don't think its 366, but we do have leap year so it could be leap year.

In Excel I'm trying to use the following:

=Year() & DAYS360("20110101","20110930")

In C# I'm using now() to get the current date. But I'm want the number of days between Jan 1st, and current date. Not sure if this is the correct prototype formula:

Prepend Two digit year format to the following
Number of Days between "20110101" and "20110930" in "YY" format

Answer Source

Instead of handling this yourself in C#, you could simply use the JulianCalendar class

And to get today in the Julian calendar, you could do:

JulianCalendar calendar = new JulianCalendar();
var today=DateTime.Today;
var dateInJulian = calendar.ToDateTime(today.Year, today.Month, today.Day, today.Hour, today.Minute, today.Second, today.Millisecond);


And I realized I didn't help you with a good way to get a result in the YYJJJ format you were looking for, it's quite simple:

var stringResult=string.Format("{0}{1}", dateInJulian.ToString("yy"), dateInJulian.DayOfYear);

Sadly, I don't think there's an equivalent of dateTime.ToString("JJJ"); that will give the day of the year, hence my little string.Format() work-around, but it works just as well!


So Phoog educated me a bit below in the comments, and pointed out that you weren't looking for today in the Julian Calendar, which is what the above code would give in respect to the JulianCalendar class. Rather, it appears you're looking for the Ordinal date (this piece added for future reader clarification). I'm going to leave the above so that someone doesn't make the same mistake that I did. What you really want, I believe, is the code from the first edit but without the JulianCalendar business, so:

var dateToConvert = DateTime.Today // Or any other date you want!
var stringResult=string.Format("{0}{1}", dateToConvert.ToString("yy"), dateToConvert.DayOfYear);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download