[英]Setting DefaultValue to first and last date of current month
如何将以下代码中的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>
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.