Reputation: 33071
Is there a format value for DateTime.ToString("") that will specify the day of the year in three digits?
For example:
Upvotes: 15
Views: 13739
Reputation: 738
I know this is a bit old, but if you absolutely, positively, have to do it in one line of code without access to the DateTime.DayOfYear
function (like I had to do today):
int myDay = floor(Now() - Date(parseInt(Now().ToString("yyyy")), 1, 1)) + 1;
Upvotes: 0
Reputation: 32276
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()
.
Upvotes: 1
Reputation: 16505
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");
Upvotes: 31