C #에서 DateTime을 매월 1 일로 설정하려면 어떻게해야합니까?
답변:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year,now.Month,1);
DateTime.Now변수에 넣고 값을 반복적으로 사용하려는 경우 사용하십시오. 이 코드가 정확히 자정 무렵에 실행되면 오류가 발생할 가능성이 적습니다. 두 번의 호출 DateTime.Now이 자정의 양쪽에서 발생하여 이상한 결과를 초래할 수 있습니다.
이런 식으로 작동합니다.
DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);
public static DateTime FirstDayOfMonth(this DateTime current)
{
return current.AddDays(1 - current.Day);
}
나는 Nick 답변을 기반으로 일부 확장 방법을 만들고 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);
}
var currentDate = DateTime.UtcNow.Date;
var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));