0

I am trying to get a label to display the Julian date in a specific format. The last two digits of the year then the day in the year, so for example January 1 2021 would be 210001. I am having difficulty getting it to display both of these values attached and making the day slot have 3 values instead of 2. This is what I have. This just gives the day of the year but still not as a 3 digit day so it shows 1 as 1 instead of 001 which is my goal Any help would be appreciated! :)

juharr
  • 31,741
  • 4
  • 58
  • 93
  • You should use DateTime format, in order to get only the information you need, and display it as you require it. – Jasc24 Jan 09 '20 at 21:42
  • @Jasc24 Unfortunately date format does not support day of the year which is what Julian day means. – juharr Jan 09 '20 at 21:43
  • Just do `dayOfYear.ToString("D3"):` to pad it to three digits with leading zeros. – juharr Jan 09 '20 at 21:46
  • 1
    I think, someone already asked something like you: https://stackoverflow.com/questions/5248827/convert-datetime-to-julian-date-in-c-sharp-tooadate-safe , this may help – Jasc24 Jan 09 '20 at 21:47
  • @Jasc24 That is not the same thing. The OP basically wants the day of the year formatted with leading zeros following the last two digits of the year. – juharr Jan 09 '20 at 21:51
  • Note that the correct terminology here is "Day of the Year" as Julian Date has other meanings. However I use to work somewhere that called this a Julian Date, or a J-Date (which is now something completely different thanks to online dating). – juharr Jan 09 '20 at 21:59

1 Answers1

2

Unfortunately the date time formats do not include anything for day of the year so you'll have to create this yourself. You can format a number to have leading zeros using the D format where you specify the length you want. You can however use the date formats to get the last two digits of the year. So the following should give you the desired formatted string for a date.

public string ToYYJJJ(DateTime date)
{
    return date.ToString("yy") + date.DayOfYear.ToString("D3");
} 
juharr
  • 31,741
  • 4
  • 58
  • 93
  • I set label1.Text = to the above statement to get it to show up in the label but it says "invalid expression 'return' ';' expected. Is there anyway to fix this? Also can I leave it under the private void? Or does it have to be public? Thank you so much for your time! – user12670728 Jan 10 '20 at 13:57
  • I'd have to see you're exact code to determine where the syntax error is. But you could just do `label1.Text = OperatorDatePicker.Value.ToString("yy") + OperatorDatePicker.Value.DayOfYear.ToString("D3");` rather than use this as a method. – juharr Jan 10 '20 at 15:22