如何:在 Calendar Web 服务器控件中以编程方式设置当前日期

更新:2007 年 11 月

默认情况下,Calendar 控件中“today”(今天)的值设置为与运行 Web 窗体页的服务器的日期相匹配的值。但是,您可能需要调整该日期,使其适应在不同的时区中查看网页的用户的需要。

以编程方式设置当前日期

  • Calendar 控件的 TodaysDate 属性设置为 DateTime 值。

    下面的示例将 TodaysDate 设置为“tomorrow”(明天),然后将 SelectedDate 设置为 TodaysDate。在浏览器中,对应于“tomorrow”(明天)的日期将突出显示。

    Dim tomorrow As Date = Date.Today.AddDays(1)
    Calendar1.TodaysDate = tomorrow
    Calendar1.SelectedDate = Calendar1.TodaysDate
    
    DateTime tomorrow = DateTime.Today.AddDays(1);
    Calendar1.TodaysDate = tomorrow;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
    

    下面的示例演示如何用选择的日期填充 DropDownList 控件并根据用户在列表中的选择设置“日历”控件中的当天日期值。

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim today As DateTime = System.DateTime.Today
            Dim yesterday As DateTime = today.AddDays(-1)
            Dim tomorrow As DateTime = 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
    End Sub
    
    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender _
            As Object, ByVal e As System.EventArgs) _
            Handles DropDownList1.SelectedIndexChanged
        Calendar1.TodaysDate = _
            Date.Parse(DropDownList1.SelectedItem.Text)
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DateTime today = System.DateTime.Today;
            DateTime yesterday = today.AddDays(-1);
            DateTime 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));
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, 
        EventArgs e)
    {
        Calendar1.TodaysDate = 
            DateTime.Parse(DropDownList1.SelectedItem.Text);
    }
    

请参见

概念

Calendar Web 服务器控件概述