Question

I have a small C# program that has a calendar and 7 labels. When I select a date the labels display the days and dates of that week.

The labels are populated using the TimeSpan string what I want to do is format this string so that it only displays the days and dates with out the times.

This is the code I have so far:

        private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
        {
            DateTime dTime = new DateTime();
            dTime = monthCalendar1.SelectionStart;
            dTime -= new TimeSpan((int)dTime.DayOfWeek, 0, 0, 0 );

            for (int i = 1; i < 8; i++)
            {
                var dt = dTime.AddDays(i);
                lb[i].Text = dt.DayOfWeek + " : " + dt.Date;                         
            }           
        }
Was it helpful?

Solution 2

You have multiple options.

You can use ToShortDateString() method for the DateTime type

lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToShortDateString()

or you can provide of a format to the ToString("format") method to specify exactly what you want it to look like.

lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToString("MM/dd/yyyy");

OTHER TIPS

You can call dt.Date.ToShortDateString().

Try with DateTime.ToShortDateString() method;

Converts the value of the current DateTime object to its equivalent short date string representation.

DateTime dt = DateTime.Now;
label8.Text = dt.Date.ToShortDateString());

You can learn more details from Custom Date and Time Format Strings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top