用户可以输入任何日期,月份和年份,如12/12 / 2013,1 / 1 / 2014,7 / 5 / 2014,5 / 1/2012,格式为MM \ DD \ YYYY格式。
如何查看日期是月份的第一个日期?
如果用户输入不是第一个月的日期,我想将该条目修改为第一个月的日期。在我的例子中,我想要
2013年12月12日至2013年12月1日 2014年1月1日为2014年1月1日(无变化) 2014年7月5日,2014年7月1日 2012年5月1日为5/1/2012(无变化)
由于
答案 0 :(得分:4)
DateTime date = ... // your original date here...
// Don't bother checking, just create a new date for the 1st.
date = new DateTime(date.Year, date.Month, 1);
更新: OP显然改变了规格:
DateTime date = ... // your original date here...
if (date.Day != 1)
date = new DateTime(date.Year, date.Month, 1).AddMonths(1);
(让.AddMonths()方法担心12月份滚动的那一年......)
答案 1 :(得分:0)
IMO,因为你对用户有一个明确的格式(MM \ DD \ YYYY),为什么不做一个简单的拆分并挖掘你的命中:
string arbitDate = "4/3/2014";
string UsersFirstDay = arbitDate.Trim().Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();//index 1 is the DD part - according to your format
UsersFirstDay = (UsersFirstDay == "1") ? UsersFirstDay : "1";
答案 2 :(得分:0)
将您的日期传递给此功能:
public static void ConvertToFirstDate(ref DateTime dt){
TimeSpan ts = dt.Subtract(new DateTime(dt.Year, dt.Month, 1));
dt = dt.AddDays(-ts.Days);
}