This documentation is archived and is not being maintained.

Setting Today's Date Programmatically in a Calendar Web Server Control

Visual Studio .NET 2003

By default, the value of "today" in the Calendar control is set to match the date of the server on which the Web Forms page runs. However, you might need to adjust the date to accommodate users who are viewing the page from a different time zone.

To set today's date programmatically

  • Set the Calendar control's TodaysDate property to a DateTime value.

    The following example sets TodaysDate to tomorrow and then set the SelectedDate to TodaysDate. In the browser, the date for tomorrow will be highlighted.

    ' Visual Basic
    Dim tomorrow As Date = Date.Today.AddDays(1)
    Calendar1.TodaysDate = tomorrow
    Calendar1.SelectedDate = Calendar1.TodaysDate
    
    // C#
    DateTime tomorrow = DateTime.Today.AddDays(1);
    Calendar1.TodaysDate = tomorrow;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
    

    The following example shows how you can prompt the user for the correct local date and then use that information to adjust the value of today's date.

    ' Visual Basic
    ' Add this the declarations section of the page class.
    Dim today As Date
    Dim tomorrow As Date
    Dim yesterday As Date   
    ' Add this to the form Load method.  
    ' The user then selects the current date from the DropDownList.
    If Not IsPostback Then   
       today = System.Date.Today
       yesterday = Today.AddDays(-1)
       tomorrow = Today.AddDays(1)
       DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
          today))
       DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
          yesterday))
       DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
          tomorrow))
    End If
    
    ' Add this code to set TodaysDate to the users selected date.
    Calendar1.TodaysDate = Date.Parse(DropDownList1.SelectedItem.Text)
    
    // C#
    // Add this to the declarations section of the page class.
    DateTime today;
    DateTime yesterday;
    DateTime tomorrow;
    
    // Add this to the Page_Load method.
    if (!IsPostBack)
    {
       today = System.DateTime.Today;
       yesterday = today.AddDays(-1);
       tomorrow = today.AddDays(1);
       DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}", 
          today));
       DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}",
          yesterday));
       DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}", 
          tomorrow));
    }
    
    // Add this code to set TodaysDate to the users selected date.
    Calendar1.TodaysDate = DateTime.Parse(DropDownList1.SelectedItem.Text);
    

See Also

Selecting Dates Programmatically in a Calendar Web Server Control | Responding to Date Selection in a Calendar Web Server Control

Show: