ultimo siguiente para mes formato fechas fecha entre dias calendario calcular algoritmo c# .net datetime date

c# - siguiente - formato fecha c



Obtenga las fechas del primer y último día del mes anterior en c# (11)

El caso de uso canónico en el comercio electrónico es la fecha de caducidad de la tarjeta de crédito, MM / aa. Resta un segundo en lugar de un día. De lo contrario, la tarjeta aparecerá expirada durante todo el último día del mes de vencimiento.

DateTime expiration = DateTime.Parse("07/2013"); DateTime endOfTheMonthExpiration = new DateTime( expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);

No puedo pensar en uno o dos delineadores fáciles que recibirían los meses previos el primer día y el último día.

Estoy LINQ-ifying una aplicación web de encuesta, y exprimieron un nuevo requisito en.

La encuesta debe incluir todas las solicitudes de servicio para el mes anterior. Entonces, si es el 15 de abril, necesito todos los ID de solicitud de Marche.

var RequestIds = (from r in rdc.request where r.dteCreated >= LastMonthsFirstDate && r.dteCreated <= LastMonthsLastDate select r.intRequestId);

No puedo pensar en las fechas fácilmente sin un interruptor. A menos que sea ciego y pase por alto un método interno para hacerlo.


Esta es una versión de la respuesta de Mike W:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth) { DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) ); DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1); if (returnLastDayOfMonth) return lastDayOfLastMonth; return firstDayOfThisMonth.AddMonths(-1); }

Puedes llamarlo así:

dateTimePickerFrom.Value = GetPreviousMonth(false); dateTimePickerTo.Value = GetPreviousMonth(true);


La forma en que hice esto en el pasado es primero obtener el primer día de este mes

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

Luego reste un día para finalizar el mes pasado

dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);

Luego reste un mes para obtener el primer día del mes anterior

dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);


Si existe la posibilidad de que sus fechas no sean fechas de calendario estrictas, debe considerar el uso de comparaciones de exclusión de enddate ... Esto evitará que se pierda ninguna solicitud creada durante la fecha del 31 de enero.

DateTime now = DateTime.Now; DateTime thisMonth = new DateTime(now.Year, now.Month, 1); DateTime lastMonth = thisMonth.AddMonths(-1); var RequestIds = rdc.request .Where(r => lastMonth <= r.dteCreated) .Where(r => r.dteCreated < thisMonth) .Select(r => r.intRequestId);


Un enfoque que usa métodos de extensión:

class Program { static void Main(string[] args) { DateTime t = DateTime.Now; DateTime p = t.PreviousMonthFirstDay(); Console.WriteLine( p.ToShortDateString() ); p = t.PreviousMonthLastDay(); Console.WriteLine( p.ToShortDateString() ); Console.ReadKey(); } } public static class Helpers { public static DateTime PreviousMonthFirstDay( this DateTime currentDate ) { DateTime d = currentDate.PreviousMonthLastDay(); return new DateTime( d.Year, d.Month, 1 ); } public static DateTime PreviousMonthLastDay( this DateTime currentDate ) { return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 ); } }

Vea este enlace http://www.codeplex.com/fluentdatetime para algunas inspiradas extensiones DateTime.


Yo uso este sencillo delineador:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date) { return date.AddDays(-date.Day); }

Tenga en cuenta que conserva el tiempo.


usando Fluent DateTime github.com/FluentDateTime/FluentDateTime

var lastMonth = 1.Months().Ago().Date; var firstDayOfMonth = lastMonth.FirstDayOfMonth(); var lastDayOfMonth = lastMonth.LastDayOfMonth();


EDITAR: ¡Esta no es la manera de hacerlo!
Si hoy.Mes - 1 = 0, como en enero, arrojará una excepción. ¡Este es claramente un caso donde ser inteligente te mete en problemas!

Un poco más simple que la respuesta aceptada :

var today = DateTime.Today var first = new DateTime(today.Year, today.Month - 1, 1); var last = new DateTime(today.Year, today.Month, 1).AddDays(-1);

Guarda una creación adicional de DateTime.


DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day); DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);


DateTime now = DateTime.Now; int prevMonth = now.AddMonths(-1).Month; int year = now.AddMonths(-1).Year; int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth); DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1); DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth); Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(), lastDayPrevMonth.ToShortDateString());


var today = DateTime.Today; var month = new DateTime(today.Year, today.Month, 1); var first = month.AddMonths(-1); var last = month.AddDays(-1);

Iníctalos si realmente necesitas una o dos líneas.