将DefaultValue设置为当前月份的第一个和最后一个日期

时间:2013-05-14 18:47:48

标签: c# asp.net

如何将以下代码中的DefaultValue设置为开始日期(第一个ControlParameter)和最后一个日期(第二个ControlParameter)当月?

<SelectParameters>
    <asp:ControlParameter ControlID="txtFromDate" Name="ExpenseDate" PropertyName="Text"
         Type="String" DefaultValue="01-05-2013" ConvertEmptyStringToNull="true" />
    <asp:ControlParameter ControlID="txtToDate" Name="ExpenseDate2" PropertyName="Text" 
         Type="String" DefaultValue="30-05-2013" ConvertEmptyStringToNull="true" />
</SelectParameters>

4 个答案:

答案 0 :(得分:16)

DateTime today = DateTime.Today;
int daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);    
DateTime endOfMonth = new DateTime(today.Year, today.Month, daysInMonth);

然后您可以将这些值设置为控件。

答案 1 :(得分:4)

DateTime now = DateTime.Now;
this.txtFromDate.Text = New DateTime(now.Year, now.Month, 1).ToString("dd-MM-yyyy");

DateTime lastDayOfMonth = now.AddMonths(1).AddDays(-1);
this.txtToDate.Text = lastDayOfMonth.ToString("dd-MM-yyyy");

我是从记忆中做到的。对于任何错误或错别字都很抱歉,但这很接近。

答案 2 :(得分:0)

如果您的示例中的日期时间格式正确,那么这应该有效:

<asp:ControlParameter ControlID="txtFromDate" 
                      Name="ExpenseDate" 
                      PropertyName="Text" 
                      Type="String" 
                      DefaultValue="<%= string.Format(CultureInfo.InvariantCulture, "01-{0:MM-yyyy}", DateTime.Today) %>" 
                      ConvertEmptyStringToNull="true" />
<asp:ControlParameter ControlID="txtToDate" 
                      Name="ExpenseDate2" 
                      PropertyName="Text" 
                      Type="String" 
                      DefaultValue="<%= string.Format(CultureInfo.InvariantCulture, "{0}-{1:MM-yyyy}", DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month), DateTime.Today) >" 
                      ConvertEmptyStringToNull="true" />

答案 3 :(得分:0)

我自己编写了一些扩展方法来处理这些情况:

public static class DateTimeExtensionMethods
{
        /// <summary>
        /// Returns the first day of the month for the given date.
        /// </summary>
        /// <param name="self">"this" date</param>
        /// <returns>DateTime representing the first day of the month</returns>
        public static DateTime FirstDayOfMonth(this DateTime self)
        {
            return new DateTime(self.Year, self.Month, 1, self.Hour, self.Minute, self.Second, self.Millisecond);
        }   // eo FirstDayOfMonth


        /// <summary>
        /// Returns the last day of the month for the given date.
        /// </summary>
        /// <param name="self">"this" date</param>
        /// <returns>DateTime representing the last of the month</returns>
        public static DateTime LastDayOfMonth(this DateTime self)
        {
            return FirstDayOfMonth(self.AddMonths(1)).AddDays(-1);
        }   // eo LastDayOfMonth
}