custom format dates in MonthCalendar control

I'm having trouble formatting output the way that I want...  I want the label to read as yyyymmdd, eg  20040716

with the code below I get close... the days and the months are not forced to 2 digits. 

How does one apply a format to the date so that it will always be in the desired format of yyyymmdd

Thanks,

Paul

===================================================

private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
label1.Text= "http://www.sec.gov/Archives/edgar/daily-index/company." + monthCalendar1.SelectionStart.Year + monthCalendar1.SelectionStart.Month + monthCalendar1.SelectionStart.Day + ".idx";
}


Answer this question

custom format dates in MonthCalendar control

  • i_dachev

    hi paul..

    by the way.. would you happen to know how to create a search based on dates ..

  • he.lin

    I think you need <strong>monthCalendar1.SelectionStart.ToString("yyyyMMdd")</strong> see the help on <strong>DateTime.ToString(...)</strong> methods, SelectionStart is of this class.
    In your code you must add <strong>.ToString("D2")</strong> to both Month and Day to force those integers into a double digit string format, see <strong>NumberFormatInfo</strong> for details (I currently can't find the place where things like "D2" is mentioned, PTB's don't be that obscure!)

  • barak

    The .ToString("D2") worked perfectly.  I think that I had tried .ToString("dd") and got a literal, so thanks for pointing this out to me...guess I was too tired at the time to think straight on this one.

    Thanks,

    Paul

  • brajoh

    Kind of a vague question so here's a vague answer

    The calendar will return a date when you click on it so you have to write code that will "capture" that value and then use it where-ever else in your code that you need it.

    For example:

    Create your Search button...add some date condition if you want (this one says "If the selected date is after today, then error message. If it is before today, then do a search."
    The search all depends on what you are looking at... a datagrid, a text box, another control of some sort....

    Paul

    private void button_Search_Click(object sender, System.EventArgs e)
    {
    if(monthCalendar1.SelectionStart.Date > DateTime.Today)
    {
    MessageBox.Show("You cannot select a date in the future.");
    }
    else if(monthCalendar1.SelectionStart.Date <= DateTime.Today)
     {
    //Do a search here
     }
    }

  • custom format dates in MonthCalendar control