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

本文关键字:第一个 最后一个 日期 设置 DefaultValue | 更新日期: 2023-09-27 18:13:48

如何将以下代码中的DefaultValue 's设置为当前月份的起始日期(第一个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>

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

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);

然后你可以设置这些值到你的控件

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");

我凭记忆做这件事。很抱歉有任何错误或拼写错误,但它接近于此。

如果在你的例子中日期时间的格式是正确的,那么这应该工作:

<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" />

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

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
}
相关文章: