¿Cuál es la forma más sencilla de obtener las fechas de comienzo y final de mes? [cerrado]

Below is the best way I have found. Thoughts? If you load this up and run is there a faster way to get it to load then what I have done here? Is there anything I am missing?

void Main()
{
    Console.WriteLine(GetMonthStart(DateTime.Now));
    Console.WriteLine(GetMonthEnd(DateTime.Now));
}
private DateTime GetMonthStart(DateTime dt)
{
    dt= dt.Date;
    return dt.Subtract(TimeSpan.FromDays(dt.Day - 1));
}
private DateTime GetMonthEnd(DateTime dt)
{
    dt= dt.Date;
    return GetMonthStart(dt).AddMonths(1).Subtract(TimeSpan.FromTicks(1));
}

preguntado el 01 de febrero de 12 a las 14:02

A question asking for opinions is not suitable to the StackExchange format. Please read our Preguntas Frecuentes. -

You might want to ask at codereview.stackexchange.com -

This seems cleaner for first day: pass the target date into dateTime: new DateTime(dateTime.Year, dateTime.Month, 1); -

1 Respuestas

Not sure if better, but I would probably do

private DateTime GetMonthStart(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, 1);
}

private DateTime GetMonthEnd(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
}

Respondido 01 Feb 12, 18:02

This would be ideal for an extension method on DateTime - Sebastián PR Gingter

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.