将DateTime设置为月份的开始
我如何设置一个DateTime到C#中的月份的第一个?
var now = DateTime.Now; var startOfMonth = new DateTime(now.Year,now.Month,1);
像这样的东西会工作
DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);
晚了一点晚,但这里有一个扩展方法,为我做了伎俩
public static class DateTimeExtensions { public static DateTime FirstDayOfMonth(this DateTime dt) { return new DateTime(dt.Year, dt.Month, 1); } }
public static DateTime FirstDayOfMonth(this DateTime current) { return current.AddDays(1 - current.Day); }
DateTime now = DateTime.Now; DateTime date = new DateTime(now.Year, now.Month, 1);
您可以使用其他任何东西而不是DateTime.Now
这应该是高效和正确的:
DateTime RoundDateTimeToMonth(DateTime time) { long ticks = time.Ticks; return new DateTime((ticks / TimeSpan.TicksPerDay - time.Day + 1) * TimeSpan.TicksPerDay, time.Kind); }
在这里, ticks / TimeSpan.TicksPerDay
返回达到给定time
和time
的完整天数。 - time.Day + 1
将此计数重置为月初。
我刚刚创build了一些基于尼克回答和SO上的其他扩展方法
public static class DateTimeExtensions { /// <summary> /// get the datetime of the start of the week /// </summary> /// <param name="dt"></param> /// <param name="startOfWeek"></param> /// <returns></returns> /// <example> /// DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday); /// DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday); /// </example> /// <remarks>http://stackoverflow.com/a/38064/428061</remarks> public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { var diff = dt.DayOfWeek - startOfWeek; if (diff < 0) diff += 7; return dt.AddDays(-1 * diff).Date; } /// <summary> /// get the datetime of the start of the month /// </summary> /// <param name="dt"></param> /// <returns></returns> /// <remarks>http://stackoverflow.com/a/5002582/428061</remarks> public static DateTime StartOfMonth(this DateTime dt) { var now = DateTime.Now; return new DateTime(now.Year, now.Month, 1); } /// <summary> /// get datetime of the start of the year /// </summary> /// <param name="dt"></param> /// <returns></returns> public static DateTime StartOfYear(this DateTime dt) { var now = DateTime.Now; return new DateTime(now.Year, 1, 1); } }
希望这可以帮助你。
textbox1.Text =“01-”+ DateTime.Now.ToString(“MMM-yyyy”);
var currentDate = DateTime.UtcNow.Date; var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));