将DateTime设置为月份的开始


97

如何在C#中将DateTime设置为每月的第一天?


本月初?
菲尔·甘

1
那么,该怎么办,..每个月的日期都以1.开始。他是否想知道本月初的一天
Shekhar_Pro 2011年

如果我们在1月显示,则应显示2011年1月1日,2月显示2011
学习

你可以看看这个
V4Vendetta

Answers:


204
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year,now.Month,1);

62
提示:DateTime.Now如果要重复使用该值,请始终放入变量中并使用该变量。如果此代码恰好在午夜左右执行,则极有可能出错。这两个呼叫DateTime.Now可能会在午夜的每一侧发生,可能会产生奇怪的影响。
FredrikMörk2011年

好点子。我认为在除夕的午夜时分可能会引起问题。
尼克·琼斯,

1
不只是新年。在每个月的最后一天的午夜会出现问题。无论如何,仅当它在月底的午夜那一纳秒执行时才有问题。但是,既然您修复了代码,现在一切都很好。
Doug S

1
为什么使用“ var”而不是“ DateTime”?
markthewizard1234

4
@ markthewizard1234主要是因为C#程序员很懒。因此,只要有三个字符,我们就尽可能使用var。还有其他原因,但我认为这是大多数人这样做的主要原因。
Tim Pohlmann

41

这样的事情会起作用

DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);

4
正如Fredrik Mork在Nick Jones的回答中所评论的那样,最好是在多次使用Datetime时将其存储在变量中,以确保该月最后一天午夜前后不会出现问题。因此:今天的DateTime = DateTime.Today; DateTime firstDay = today.AddDays(1-today.Day);
Doug S

9
public static DateTime FirstDayOfMonth(this DateTime current)
{
    return current.AddDays(1 - current.Day);
}

1
这样比较好,因为它可以保留时区。
Rosdi Kasim

8

开派对有点晚,但这是一种扩展方法,对我有用

public static class DateTimeExtensions
{
  public static DateTime FirstDayOfMonth(this DateTime dt)
  {
    return new DateTime(dt.Year, dt.Month, 1);
  }
}

1
问题在于它不保留原始时区。
Mike Cole

2
DateTime now = DateTime.Now;
DateTime date = new DateTime(now.Year, now.Month, 1);

您可以使用其他任何东西代替DateTime.Now


2

我刚刚根据尼克答案创建了一些扩展方法,并在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);

}

0

这应该是有效且正确的:

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.Day + 1此计数重置为月初。


0

希望对您有帮助。

textbox1.Text =“ 01-” + DateTime.Now.ToString(“ MMM-yyyy”);


-2
var currentDate = DateTime.UtcNow.Date;
var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));

3
这与fubo的答案完全相同,您不觉得吗?
Thomas Ayoub

2
尽管此代码可以解决问题,但始终建议添加解释说明其原因/工作方式的解释。
BDL

@ThomasAyoub-不,这不是fubo答案的相当重复,因为它不包含时间portain。
杰伊·沙

@BDL-我认为这很容易理解,不需要解释。但是,仅供参考,我已经选择了当前的Utc日期,然后从中减去(当前日期的天数-1)以获得月份的开始日期,即1(不是0,这就是为什么我减去1)。是的,这肯定会解决问题。
杰伊·沙
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.