public static DateTime RoundMinutes(this DateTime dateTime) { dateTime.AddSeconds(-dateTime.Second); dateTime.AddMilliseconds(-dateTime.Millisecond); var remainder = dateTime.Minute % 15; dateTime = dateTime.AddMinutes(remainder * -1); if (remainder > 7) { dateTime = dateTime.AddMinutes(15); } return dateTime; }
public static DateTime AddType(this DateTime instance, TimeUnits type, double increment) { DateTime result = instance; switch (type) { case TimeUnits.Days: result = instance.AddDays(increment); break; case TimeUnits.Months: increment *= DateTime.DaysInMonth(instance.Year, instance.Month); result = instance.AddDays((int)(Math.Floor(increment))); break; case TimeUnits.Weeks: result = instance.AddDays(increment * 7); break; case TimeUnits.Years: if (DateTime.IsLeapYear(instance.Year)) increment *= 366; else increment *= 365; result = instance.AddDays((int)(Math.Floor(increment))); break; case TimeUnits.Hours: result = instance.AddHours(increment); break; case TimeUnits.Minutes: result = instance.AddMinutes(increment); break; } return result; }
public static DateTime Interval(this DateTime date, DateTimePart? intervalType, int? intervalVal) { if (intervalType.HasValue && intervalVal.HasValue) { switch (intervalType.Value) { case DateTimePart.Year: return date.AddYears(intervalVal.Value); case DateTimePart.Month: return date.AddMonths(intervalVal.Value); case DateTimePart.Day: return date.AddDays((double)intervalVal.Value); case DateTimePart.Hour: return date.AddHours((double)intervalVal.Value); case DateTimePart.Munite: return date.AddMinutes((double)intervalVal.Value); case DateTimePart.Second: return date.AddSeconds((double)intervalVal.Value); case DateTimePart.Week: return date.AddDays((double)intervalVal.Value * 7); case DateTimePart.Quarter: return date.AddMonths(intervalVal.Value * 3); } } return date; }
/////////////////////////////////////////////////////////////////////// public static DateTime NextMinute(this DateTime date) { DateTime next = date.AddMinutes(1); next = next.SetSecond(0); next = next.SetMillisecond(0); return next; }
/// <summary> /// Generates a PartitionKey representation (in reverse order) based on the specified <see cref="DateTime"/>. /// </summary> /// <param name="dateTime">The DateTime.</param> /// <returns>A string representing the Partition Key (in reverse order).</returns> public static string GeneratePartitionKeyReversed(this DateTime dateTime) { dateTime = dateTime.AddMinutes(-1D); var pk = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0); return GetTicksReversed(pk); }
public static DateTime Round(this DateTime dateTime) { DateTime result = dateTime.AddMinutes(dateTime.Minute >= 30 ? (60 - dateTime.Minute) : (30 - dateTime.Minute)); result = result.AddSeconds(-1 * result.Second); // To reset seconds to 0 result = result.AddMilliseconds(-1 * result.Millisecond); // To reset milliseconds to 0 return result; }
/// <summary> /// Converts the specified client time to UTC Date Time. /// </summary> /// <param name="dateTime">Date time object to be converted.</param> /// <returns>Date time in UTC time zone.</returns> public static DateTime ToUTCFromClientTime(this DateTime dateTime) { var timeOffSet = HttpContext.Current.Session["__TimezoneOffset"]; if (timeOffSet != null) { var offset = int.Parse(timeOffSet.ToString()); dateTime = dateTime.AddMinutes(1 * offset); } return dateTime; }
/// <summary> /// Rounds the minute component to the nearest specified time. Defaults to 1 hour /// </summary> /// <param name="source"></param> /// <param name="rounding"></param> /// <returns></returns> public static DateTime RoundMinutes(this DateTime source, MinuteRounding rounding = MinuteRounding.Hour) { if (rounding == MinuteRounding.QuarterHour) throw new NotImplementedException("Coming soon"); switch (rounding) { case MinuteRounding.Hour: if (source.Minute >= 30) return source.AddHours(1).AddMinutes(-source.Minute).TrimSeconds(); return source.AddMinutes(-source.Minute).TrimSeconds(); case MinuteRounding.HalfHour: if (source.Minute < 15) return source.AddMinutes(-source.Minute).TrimSeconds(); if (source.Minute >= 15 && source.Minute < 45) return source.AddMinutes(-source.Minute).AddMinutes(30).TrimSeconds(); return source.AddHours(1).AddMinutes(-source.Minute).TrimSeconds(); default: throw new ArgumentOutOfRangeException("rounding"); } }
public static DateTime LocalToUtc(this DateTime local, int utcOffset) { if (local != DateTime.MinValue && local != DateTime.MaxValue) { try { return local.AddMinutes(0 - utcOffset); } catch { } } return local; }
// Convert the passed datetime into client timezone. public static string ToClientTime(this DateTime dt) { var timeOffSet = HttpContext.Current.Session["timezoneoffset"]; // read the value from session if (timeOffSet != null) { var offset = int.Parse(timeOffSet.ToString()); dt = dt.AddMinutes(-1 * offset); return dt.ToString(); } // if there is no offset in session return the datetime in server timezone return dt.ToLocalTime().ToString(); }
/// <summary> /// Adds a generic AddType to a DateTime object /// </summary> /// <param name="now"><seealso cref="System.DateTime"/></param> /// <param name="adder">Type structure that acts as a switcher for what type of add to perform</param> /// <param name="much">How much AddType to add to each element for creating list of data</param> /// <returns>A DateTime object with the added AddType amounts</returns> public static DateTime Add(this DateTime now, AddType adder, double much) { DateTime ret = now; switch (adder) { case AddType.Years: { ret = now.AddYears((int)much); break; } case AddType.Months: { ret = now.AddMonths((int)much); break; } case AddType.Days: { ret = now.AddDays(much); break; } case AddType.Hours: { ret = now.AddHours(much); break; } case AddType.Minutes: { ret = now.AddMinutes(much); break; } case AddType.Seconds: { ret = now.AddSeconds(much); break; } case AddType.Milliseconds: { ret = now.AddMilliseconds(much); break; } case AddType.Ticks: { ret = now.AddTicks((long)much); break; } } return ret; }
public static IEnumerable<DateTime> GetQuarterHourIncrementsAfter(this DateTime dateTime, bool wrap = true) { var quarterHours = new List<DateTime>(QuarterHoursInDay); for (int i = 1; i <= QuarterHoursInDay; i++) { var newDateTime = dateTime.AddMinutes(i * 15); if (!wrap && newDateTime.Date.CompareTo(dateTime.Date) > 0) { break; } quarterHours.Add(newDateTime); } return quarterHours; }
public static DateTime SubstractTimeStepUnit(this DateTime dt, TimeStepUnit tstep) { switch (tstep) { case TimeStepUnit.Year: return dt.AddYears(-1); case TimeStepUnit.Month: return dt.AddMonths(-1); case TimeStepUnit.Day: return dt.AddDays(-1); case TimeStepUnit.Hour: return dt.AddHours(-1); case TimeStepUnit.Minute: return dt.AddMinutes(-1); case TimeStepUnit.Second: return dt.AddSeconds(-1); } return dt; }
public static bool MatchesCronExpression(this DateTime theDateTime, string cronExpression) { CrontabSchedule schedule; ExceptionProvider ex; var valueOrException = CrontabSchedule.TryParse(cronExpression, input => { schedule = input; return true; }, exception => { ex = exception; ex.Invoke(); return false; }); var cronSchedule = CrontabSchedule.Parse(cronExpression); var nextOccurrence = cronSchedule.GetNextOccurrence(theDateTime.AddMinutes(-1).AddSeconds(-1 * theDateTime.Second)); var matches = Math.Abs((theDateTime.AddSeconds(-1*theDateTime.Second) - nextOccurrence).TotalMinutes) < 1 ; return matches; }
public static DateTime NearestQuarterHour(this DateTime source) { var Mins = source.Minute; int Upper = 15; bool Found = false; while (!Found) { if (Mins < (Upper - 10)) { Mins = Upper - 15; Found = true; } else if (Mins < Upper) { Mins = Upper; Found = true; } Upper = Upper + 15; } return source.AddMinutes((source.Minute * -1) + Mins); }
/// <summary> /// Returns a DateTime a number of minutes in the future. /// </summary> /// <param name="self">The DateTime to move</param> /// <param name="minutes">Number of minutes</param> public static DateTime MinutesSince(this DateTime self, double minutes) { return self.AddMinutes(minutes); }
/// <summary> /// Returns a DateTime a number of minutes in the past /// </summary> /// <param name="self">The DateTime to move</param> /// <param name="minutes">Number of minutes</param> public static DateTime MinutesAgo(this DateTime self, double minutes) { return self.AddMinutes(-minutes); }
public static string TimeDuration(this DateTime sourcedate, int duration) { var startTime = String.Empty; var endTime = String.Empty; if (sourcedate.Minute == 0) { startTime = sourcedate.ToString("hh tt"); endTime = duration % 60 > 0 ? sourcedate.AddMinutes(duration).ToString("hh:mm tt") : sourcedate.AddMinutes(duration).ToString("hh tt"); } else { startTime = sourcedate.ToString("hh:mm tt"); endTime = sourcedate.AddMinutes(duration).ToString("hh:mm tt"); } if (startTime.Equals(endTime)) return startTime; return startTime + " - " + endTime; }
/// <summary> /// Adds 30 minutes to the given DateTime. /// </summary> /// <param name="date">The given DateTime.</param> /// <returns>The DateTime after 30 minutes are added.</returns> public static DateTime AddHalfAnHour(this DateTime date) { return date.AddMinutes(30); }
/// <summary> /// Subtracts given minutes from the given DateTime. /// </summary> /// <param name="date">The given DateTime.</param> /// <param name="minutes">Number of minutes to be subtracted.</param> /// <returns>The DateTime after the given minutes are subtracted.</returns> public static DateTime SubtractMinutes(this DateTime date, int minutes) { return date.AddMinutes(minutes.Negate()); }
/// <summary> /// Adds one minute to the given DateTime. /// </summary> /// <param name="date">The given DateTime.</param> /// <returns>The DateTime after one minute is added.</returns> public static DateTime AddAMinute(this DateTime date) { return date.AddMinutes(1); }
public static DateTime SubtractMinutes(this DateTime date, double value) { if (value < 0) throw new ArgumentException("Value cannot be less than 0.", "value"); return date.AddMinutes(value * -1); }
/// <summary> /// 获取下一个交易分钟 /// </summary> /// <param name="self"></param> /// <returns></returns> public static DateTime ToNextTradingMinute(this DateTime self) { if (self.IsTradingDate() == false) { self = self.ToNextTradingDate(); return self.AddHours(9).AddMinutes(31); } DateTime time = self.AddMinutes(1); TimeSpan span = time.TimeOfDay; if (span < new TimeSpan(9, 31, 0)) { return time.Date.AddHours(9).AddMinutes(31); } else if (span > new TimeSpan(11, 30, 0) && span < new TimeSpan(13, 0, 0)) { return time.Date.AddHours(13).AddMinutes(1); } else if (span > new TimeSpan(15, 0, 0)) { return time.Date.AddDays(1).ToNextTradingMinute(); } return time; }
/// <summary> /// Rounds the second component to the nearest specified time. Defaults to 1 second /// </summary> /// <param name="source"></param> /// <param name="rounding"></param> /// <returns></returns> public static DateTime RoundSeconds(this DateTime source, SecondRounding rounding = SecondRounding.Second) { switch (rounding) { case SecondRounding.Second: if (source.Second >= 30) return source.AddMinutes(1).TrimSeconds(); return source.AddSeconds(-source.Second).AddMilliseconds(-source.Millisecond); case SecondRounding.HalfSecond: if (source.Second < 15) return source.TrimSeconds(); if (source.Second >= 15 && source.Minute < 45) return source.TrimSeconds().AddSeconds(30); return source.AddMinutes(1).TrimSeconds(); default: throw new ArgumentOutOfRangeException("rounding"); } }
public static DateTime SubtractMinutes(this DateTime dateTime, long minutes) { return dateTime.AddMinutes(minutes * -1); }
public static DateTime SubtractMinutes(this DateTime dateTime, double minutes) { return dateTime.AddMinutes(-minutes); }
public static DateTime TurnToMultiplesOf5(this DateTime value) { if (value.Second > 0) value = DateTime.Parse(value.ToString("yyyy/MM/dd HH:mm:00")); var mod = -value.Minute % 5; return mod == 0 ? value : value.AddMinutes(mod); }
/// <summary> /// Warning: bug found. dt.Offset may be incorrect as offsets could be different if range crosses daylight saving switch, i.e. October - December, or month of November in the EST USA. /// </summary> /// <param name="dt"></param> /// <param name="count"></param> /// <param name="unit"></param> /// <returns></returns> public static DateTimeOffset Add(this DateTimeOffset dt, int count, TimeUnits unit) { switch(unit) { case TimeUnits.Century: return dt.AddYears(count*100); case TimeUnits.Day: return dt.AddDays(count); case TimeUnits.Decade: return dt.AddYears(count*10); case TimeUnits.Hour: return dt.AddHours(count); case TimeUnits.Minute: return dt.AddMinutes(count); case TimeUnits.Month: return dt.AddMonths(count); case TimeUnits.Quarter: return dt.AddMonths(count*3); case TimeUnits.Second: return dt.AddSeconds(count); case TimeUnits.Week: return dt.AddDays(count*7); case TimeUnits.Year: return dt.AddYears(count); } throw new Exception("Adding \"{0}\" is not implemented.".SmartFormat(unit)); }
internal static DateTime ClearMinutesAndSeconds(this DateTime current) { return current.AddMinutes(-1 * current.Minute) .AddSeconds(-1 * current.Second) .AddMilliseconds(-1 * current.Millisecond); }
public static DateTime ChangeMinute(this DateTime date, int minute) { if (minute < 0 || minute > 59) throw new ArgumentException("Value must be between 0 and 59.", "minute"); return date.AddMinutes(minute - date.Minute); }