Reputation: 11725
How can I set a DateTime to the first of the month in C#?
Upvotes: 110
Views: 109586
Reputation: 6787
I've just create some extension methods based on Nick answer and others on the 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 System.DateTime StartOfWeek(this System.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 System.DateTime StartOfMonth(this System.DateTime dt) =>
new System.DateTime(dt.Year, dt.Month, 1);
/// <summary>
/// get datetime of the start of the year
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static System.DateTime StartOfYear(this System.DateTime dt) =>
new System.DateTime(dt.Year, 1, 1);
}
Upvotes: 2
Reputation: 69
Hope this helps you.
textbox1.Text = "01-" + DateTime.Now.ToString("MMM-yyyy");
Upvotes: 0
Reputation: 3771
var currentDate = DateTime.UtcNow.Date;
var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));
Upvotes: -2
Reputation: 6493
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year,now.Month,1);
Upvotes: 220
Reputation: 45947
public static DateTime FirstDayOfMonth(this DateTime current)
{
return current.AddDays(1 - current.Day);
}
Upvotes: 15
Reputation: 891
A bit late to the party but here's an extension method that did the trick for me
public static class DateTimeExtensions
{
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
}
Upvotes: 9
Reputation: 83
This should be efficient and correct:
DateTime RoundDateTimeToMonth(DateTime time)
{
long ticks = time.Ticks;
return new DateTime((ticks / TimeSpan.TicksPerDay - time.Day + 1) * TimeSpan.TicksPerDay, time.Kind);
}
Here ticks / TimeSpan.TicksPerDay
returns count of full days up to given time
and - time.Day + 1
resets this count to the beginning of month.
Upvotes: 0
Reputation: 38210
Something like this would work
DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);
Upvotes: 42
Reputation: 1651
DateTime now = DateTime.Now;
DateTime date = new DateTime(now.Year, now.Month, 1);
You can use anything else instead of DateTime.Now
Upvotes: 2