C# 在日期中设置特定日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13927715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting A particular Day in a date
提问by Rahul2788
I am using Calender Extender Control in the AjaxControlToolkit. There are basically 2 controls of date : Start Dateand End date(both associated with calender extender). Based on start Date selected, I populate date in the end date field like adding no of months or days. But like I have been able to add months, but also wants to set a particular day of that month which I am unable to do.
我在 AjaxControlToolkit 中使用 Calender Extender Control。基本上有 2 个日期控件:Start Date和End date(均与压光机扩展器相关)。根据选择的开始日期,我在结束日期字段中填充日期,例如添加月数或天数。但是就像我已经能够添加月份一样,但也想设置该月的特定日期而我无法做到。
Example:
Today date is 18 Dec 2012. Something like 1st of every three months, So I add 3 months the month comes out to be Feb 2013. But I want to set Day 1st Feb 2013. I am unable to do it. Kindly help.
示例:今天日期是18 Dec 2012。类似于每三个月的第一天,所以我加了 3 个月,结果是Feb 2013。但我想设置 Day 1st Feb 2013。我做不到。请帮忙。
采纳答案by Naresh Pansuriya
You can set whatever day of month by add month.
您可以通过添加月份设置月份中的任何一天。
DateTime todayDate = DateTime.Now;
DateTime after3MonthDate = todayDate.AddMonths(3);
//Set First Day of Month
after3MonthDate = new DateTime(after3MonthDate.Year, after3MonthDate.Month, 1);
回答by pala?н
Try this:
尝试这个:
// Here is the simple wrapper method to get the first day of the month:
public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
// Set the due date...
DueDate.Text = (FirstDayOfMonthFromDateTime(DateTime.Parse(StartDate.Text).AddMonths(N))).ToShortDateString();
You can also modify the wrapper method to get any day of the month:
您还可以修改包装器方法以获取一个月中的任何一天:
public DateTime DayOfMonthFromDateTime(DateTime dateTime, int day)
{
return new DateTime(dateTime.Year, dateTime.Month, day);
}
回答by st_stefanov
This code can be used for existing date time variable to set the day part to the first day of the month:
此代码可用于现有日期时间变量以将日期部分设置为该月的第一天:
if(myDate.Day > 1)
{
myDate = myDate.AddDays(-(myDate.Day - 1));
}

