C# DateTime Custom Formatting for Seasons
I've come across a problem customizing my DateTimePicker value in my
application. I've read all about the various formatting strings which you
can use to customize the way the date/time is interpreted. The issue is
that I actually want some of the text to be ignored in the custom format
string so that I can add in the season as a string to the beginning of the
DateTimePicker.
For example, let's take today's date which is August 7th, 2013 at 5:30PM
(in the US). If I use the custom format string "MMM.d -h:mm tt" then the
date will be shown as Aug. 7th - 5:30PM. So, that's perfect. Only, I want
to add the season to the beginning of the string. So, in this case, it
would be "Summer: Aug. 7th - 5:30PM".
The issue that I'm having is that if I insert the word "Summer" at the
beginning of the custom format string, then it actually interprets the
double mm's as GetMinute value of the dateTime. I'd like for the season to
remain literal, but the rest of the format string to be interpreted (if
that makes sense).
Here is the code I'm using:
public Form1()
{
InitializeComponent();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
season = getSeason(dateTimePicker1.Value);
dateTimePicker1.CustomFormat = convertSeason(season) + " : " + dt_format;
}
public int season = 1; //set default to summer
public string dt_format = "MMM.d -h:mm tt";
private int getSeason(DateTime date)
{
float value = (float)date.Month + date.Day / 100; // <month>.<day(2
digit)>
if (value < 3.21 || value >= 12.22) return 3; // Winter
if (value < 6.21) return 0; // Spring
if (value < 9.23) return 1; // Summer
return 2; // Autumn
}
private string convertSeason(int value)
{
string season = "Spring";
if (value == 1) season = "Summer";
else if (value == 2) season = "Autumn";
else if (value == 3) season = "Winter";
return season;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
season = getSeason(dateTimePicker1.Value);
dateTimePicker1.CustomFormat = convertSeason(season) + " : " + dt_format;
}
No comments:
Post a Comment