public static DateTimeOffset GetWithMaximumMonth(this DateTimeOffset dateTime, TimeZoneInfo timeZone = null) { var daysInMonth = Calendar.GetDaysInMonth(dateTime.Year, 12); if (dateTime.Day < daysInMonth) { daysInMonth = dateTime.Day; } if (timeZone == null) { return(new DateTimeOffset( dateTime.Year, 12, daysInMonth, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Offset)); } return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, 12, daysInMonth, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, timeZone)); }
/// <summary> /// Check if this is a valid date. /// </summary> /// <param name="day"></param> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> private static bool CheckDayValidInMonth(TimeZoneInfo timeZone, int day, int month, int year) { try { DateTimeOffsetHelper.CreateDateTime(year, month, day, 0, 0, 0, 0, timeZone); return(true); } catch (ArgumentException) { return(false); } }
/// <summary> /// Sets the field value. /// </summary> /// <param name="dateTime">The date time.</param> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="timeZone">The time zone.</param> /// <returns></returns> /// <exception cref="ArgumentException">invalid datetime</exception> public static DateTimeOffset SetFieldValue(this DateTimeOffset dateTime, int field, int value, TimeZoneInfo timeZone) { switch (field) { case DateTimeFieldEnum.MILLISEC: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, value, timeZone)); case DateTimeFieldEnum.SECOND: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, value, dateTime.Millisecond, timeZone)); case DateTimeFieldEnum.MINUTE: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, value, dateTime.Second, dateTime.Millisecond, timeZone)); case DateTimeFieldEnum.HOUR_OF_DAY: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, dateTime.Month, dateTime.Day, value, dateTime.Minute, dateTime.Second, dateTime.Millisecond, timeZone)); case DateTimeFieldEnum.DATE: case DateTimeFieldEnum.DAY_OF_MONTH: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, dateTime.Month, value, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, timeZone)); case DateTimeFieldEnum.MONTH: return(DateTimeOffsetHelper.CreateDateTime( dateTime.Year, value, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, timeZone)); case DateTimeFieldEnum.YEAR: return(DateTimeOffsetHelper.CreateDateTime( value, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, timeZone)); default: throw new ArgumentException("invalid datetime"); } }