Is there a format value for DateTime.ToString("") that will specify the day of the year in three digits?
For example:
- Jan 1, 2012 would be 001
- Feb 1, 2012 would be 032
- Dec 31, 2012 would be 366 (leap year)
- Dec 31, 2011 would be 365
No, you can use DateTime.DayOfYear.ToString("000");
Your examples:
new DateTime(2012, 1, 1).DayOfYear.ToString("000");
new DateTime(2012, 2, 1).DayOfYear.ToString("000");
new DateTime(2012, 12, 31).DayOfYear.ToString("000");
new DateTime(2011, 12, 31).DayOfYear.ToString("000");
I needed a way to allow users to give a format that could handle the day of the year and I came up with the following code.
public static string FormatDate(this DateTime date, string format)
{
var builder = new StringBuilder();
int numOfjs = 0;
bool escaped = false;
foreach (char c in format)
{
if (c == 'j' && !escaped)
{
numOfjs++;
}
else
{
if (c == 'j' && escaped)
{
builder.Remove(builder.Length - 1, 1);
}
if (numOfjs > 0)
{
var dayOfYearFormat = new string('0', Math.Min(3, numOfjs));
builder.Append(date.DayOfYear.ToString(dayOfYearFormat));
}
numOfjs = 0;
builder.Append(c);
}
escaped = c == '\\' && !escaped;
}
if (numOfjs > 0)
{
var dayOfYearFormat = new string('0', Math.Min(3, numOfjs));
builder.Append(date.DayOfYear.ToString(dayOfYearFormat));
}
return date.ToString(builder.ToString());
}
This allows you to have a format that will replace consecutive un-delimited letter j's with the day of the year. It will zero pad up to 3 digits based on the number of j's. More than 3 consecutive j's act like just 3.
It basically rewrites the format to replace delimited j's with just a j, and consecutive j's with the day of the year. It then passes this new format to DateTime.ToString()
.