public void DaysInMonth() { DateTime d = new DateTime(2008, 02, 28); int x = d.DaysInMonth(); DateTime e = new DateTime(2010, 02, 28); int y = e.DaysInMonth(); Assert.AreEqual(29, x); Assert.AreEqual(28, y); }
// Match several other cases // Including 'today', 'the day after tomorrow', 'on 13' private DateTimeResolutionResult ParseImplicitDate(string text, DateObject referenceDate) { var trimmedText = text.Trim(); var ret = new DateTimeResolutionResult(); // Handle "on 12" var match = this.config.OnRegex.Match(this.config.DateTokenPrefix + trimmedText); if (match.Success && match.Index == 3 && match.Length == trimmedText.Length) { int month = referenceDate.Month, year = referenceDate.Year; var dayStr = match.Groups["day"].Value; var day = this.config.DayOfMonth[dayStr]; ret.Timex = DateTimeFormatUtil.LuisDate(-1, -1, day); DateObject futureDate, pastDate; var tryStr = DateTimeFormatUtil.LuisDate(year, month, day); if (DateObject.TryParse(tryStr, out DateObject _)) { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); pastDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); if (futureDate < referenceDate) { futureDate = futureDate.AddMonths(+1); } if (pastDate >= referenceDate) { pastDate = pastDate.AddMonths(-1); } } else { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month + 1, day); pastDate = DateObject.MinValue.SafeCreateFromValue(year, month - 1, day); } ret.FutureValue = futureDate; ret.PastValue = pastDate; ret.Success = true; return(ret); } // Handle "today", "the day before yesterday" var exactMatch = this.config.SpecialDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var swift = GetSwiftDay(exactMatch.Value); var value = referenceDate.Date.AddDays(swift); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = value; ret.Success = true; return(ret); } // Handle "two days from tomorrow" exactMatch = this.config.SpecialDayWithNumRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var swift = GetSwiftDay(exactMatch.Groups["day"].Value); var numErs = this.config.IntegerExtractor.Extract(trimmedText); var numOfDays = Convert.ToInt32((double)(this.config.NumberParser.Parse(numErs[0]).Value ?? 0)); var value = referenceDate.AddDays(numOfDays + swift); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "two sundays from now" exactMatch = this.config.RelativeWeekDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var numErs = this.config.IntegerExtractor.Extract(trimmedText); var num = Convert.ToInt32((double)(this.config.NumberParser.Parse(numErs[0]).Value ?? 0)); var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate; // Check whether the determined day of this week has passed. if (value.DayOfWeek > (DayOfWeek)this.config.DayOfWeek[weekdayStr]) { num--; } while (num-- > 0) { value = value.Next((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "next Sunday", "upcoming Sunday" // We define "upcoming Sunday" as the nearest Sunday to come (not include today) // We define "next Sunday" as Sunday of next week exactMatch = this.config.NextRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.Next((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (this.config.UpcomingPrefixRegex.MatchBegin(trimmedText, trim: true).Success) { value = referenceDate.Upcoming((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "this Friday" exactMatch = this.config.ThisRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.This((DayOfWeek)this.config.DayOfWeek[weekdayStr]); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "last Friday", "last mon" // We define "past Sunday" as the nearest Sunday that has already passed (not include today) // We define "previous Sunday" as Sunday of previous week exactMatch = this.config.LastRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.Last((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (this.config.PastPrefixRegex.MatchBegin(trimmedText, trim: true).Success) { value = referenceDate.Past((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "Friday" exactMatch = this.config.WeekDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[weekdayStr]; var value = referenceDate.This((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (weekDay == 0) { weekDay = 7; } if (weekDay < (int)referenceDate.DayOfWeek) { value = referenceDate.Next((DayOfWeek)weekDay); } ret.Timex = "XXXX-WXX-" + weekDay; var futureDate = value; var pastDate = value; if (futureDate < referenceDate) { futureDate = futureDate.AddDays(7); } if (pastDate >= referenceDate) { pastDate = pastDate.AddDays(-7); } ret.FutureValue = DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day); ret.PastValue = DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day); ret.Success = true; return(ret); } // Handle "for the 27th." match = this.config.ForTheRegex.Match(text); if (match.Success) { int day = 0, month = referenceDate.Month, year = referenceDate.Year; var dayStr = match.Groups["DayOfMonth"].Value; // Create a extract result which content ordinal string of text ExtractResult er = new ExtractResult { Text = dayStr, Start = match.Groups["DayOfMonth"].Index, Length = match.Groups["DayOfMonth"].Length, }; day = Convert.ToInt32((double)(this.config.NumberParser.Parse(er).Value ?? 0)); ret.Timex = DateTimeFormatUtil.LuisDate(-1, -1, day); DateObject futureDate; var tryStr = DateTimeFormatUtil.LuisDate(year, month, day); if (DateObject.TryParse(tryStr, out DateObject _)) { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month + 1, day); } ret.FutureValue = futureDate; ret.PastValue = ret.FutureValue; ret.Success = true; return(ret); } // Handling cases like 'Thursday the 21st', which both 'Thursday' and '21st' refer to a same date match = this.config.WeekDayAndDayOfMothRegex.Match(text); if (match.Success) { int month = referenceDate.Month, year = referenceDate.Year; // create a extract result which content ordinal string of text ExtractResult extractResultTmp = new ExtractResult { Text = match.Groups["DayOfMonth"].Value, Start = match.Groups["DayOfMonth"].Index, Length = match.Groups["DayOfMonth"].Length, }; // parse the day in text into number var day = Convert.ToInt32((double)(this.config.NumberParser.Parse(extractResultTmp).Value ?? 0)); // The validity of the phrase is guaranteed in the Date Extractor ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Success = true; return(ret); } // Handling cases like 'Monday 21', which both 'Monday' and '21' refer to the same date. // The year of expected date can be different to the year of referenceDate. match = this.config.WeekDayAndDayRegex.Match(text); if (match.Success) { int month = referenceDate.Month, year = referenceDate.Year; // Create a extract result which content ordinal string of text ExtractResult ertmp = new ExtractResult { Text = match.Groups["day"].Value, Start = match.Groups["day"].Index, Length = match.Groups["day"].Length, }; // Parse the day in text into number var day = Convert.ToInt32((double)(this.config.NumberParser.Parse(ertmp).Value ?? 0)); // Firstly, find a latest date with the "day" as pivotDate. // Secondly, if the pivotDate equals the referenced date, in other word, the day of the referenced date is exactly the "day". // In this way, check if the pivotDate is the weekday. If so, then the futureDate and the previousDate are the same date (referenced date). // Otherwise, increase the pivotDate month by month to find the latest futureDate and decrease the pivotDate month // by month to the latest previousDate. // Notice: if the "day" is larger than 28, some months should be ignored in the increase or decrease procedure. var pivotDate = new DateObject(year, month, 1); var daysInMonth = DateObject.DaysInMonth(year, month); if (daysInMonth >= day) { pivotDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { // Add 1 month is enough, since 1, 3, 5, 7, 8, 10, 12 months has 31 days pivotDate = pivotDate.AddMonths(1); pivotDate = DateObject.MinValue.SafeCreateFromValue(pivotDate.Year, pivotDate.Month, day); } var numWeekDayInt = (int)pivotDate.DayOfWeek; var extractedWeekDayStr = match.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[extractedWeekDayStr]; if (!pivotDate.Equals(DateObject.MinValue)) { if (day == referenceDate.Day && numWeekDayInt == weekDay) { // The referenceDate is the weekday and with the "day". ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); } else { var futureDate = pivotDate; var pastDate = pivotDate; while ((int)futureDate.DayOfWeek != weekDay || futureDate.Day != day || futureDate < referenceDate) { // Increase the futureDate month by month to find the expected date (the "day" is the weekday) and // make sure the futureDate not less than the referenceDate. futureDate = futureDate.AddMonths(1); var tmp = DateObject.DaysInMonth(futureDate.Year, futureDate.Month); if (tmp >= day) { // For months like January 31, after add 1 month, February 31 won't be returned, so the day should be revised ASAP. futureDate = futureDate.SafeCreateFromValue(futureDate.Year, futureDate.Month, day); } } ret.FutureValue = futureDate; while ((int)pastDate.DayOfWeek != weekDay || pastDate.Day != day || pastDate > referenceDate) { // Decrease the pastDate month by month to find the expected date (the "day" is the weekday) and // make sure the pastDate not larger than the referenceDate. pastDate = pastDate.AddMonths(-1); var tmp = DateObject.DaysInMonth(pastDate.Year, pastDate.Month); if (tmp >= day) { // For months like March 31, after minus 1 month, February 31 won't be returned, so the day should be revised ASAP. pastDate = pastDate.SafeCreateFromValue(pastDate.Year, pastDate.Month, day); } } ret.PastValue = pastDate; if (weekDay == 0) { weekDay = 7; } ret.Timex = "XXXX-WXX-" + weekDay; } } ret.Success = true; return(ret); } return(ret); }
/// <summary> /// Returns TRUE if the date given is valid; otherwise returns FALSE. /// Checks the validity of the date formed by the arguments. /// </summary> /// <remarks> /// A date is considered valid if: /// <list type="bullet"> /// <item>year is between 1 and 32767 inclusive</item> /// <item>month is between 1 and 12 inclusive</item> /// <item>day is within the allowed number of days for the given month. Leap years are taken into consideration.</item> /// </list> /// </remarks> /// <param name="month">Month</param> /// <param name="day">Day</param> /// <param name="year">Year</param> /// <returns>True if the date is valid, false otherwise.</returns> public static bool checkdate(int month, int day, int year) { return(month >= 1 && month <= 12 && year >= 1 && year <= 32767 && day >= 1 && day <= System_DateTime.DaysInMonth(year, month)); // this works also with leap years }
internal static string FormatDate(string format, System_DateTime utc, TimeZoneInfo zone) { Debug.Assert(zone != null); if (format == null) { return(string.Empty); } var local = TimeZoneInfo.ConvertTime(utc, zone); // here we are creating output string StringBuilder result = new StringBuilder(); bool escape = false; foreach (char ch in format) { if (escape) { result.Append(ch); escape = false; continue; } switch (ch) { case 'a': // Lowercase Ante meridiem and Post meridiem - am or pm result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo).ToLowerInvariant()); break; case 'A': // Uppercase Ante meridiem and Post meridiem - AM or PM result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo)); break; case 'B': // Swatch Beat (Internet Time) - 000 through 999 result.AppendFormat("{0:000}", GetSwatchBeat(utc)); break; case 'c': { // ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00 result.Append(local.ToString("yyyy-MM-dd'T'HH:mm:ss", DateTimeFormatInfo.InvariantInfo)); TimeSpan offset = zone.GetUtcOffset(local); result.AppendFormat("{0}{1:00}:{2:00}", (offset.Ticks < 0) ? "" /*offset.Hours already < 0*/ : "+", offset.Hours, offset.Minutes); break; } case 'd': // Day of the month, 2 digits with leading zeros - 01 to 31 result.Append(local.ToString("dd", DateTimeFormatInfo.InvariantInfo)); break; case 'e': // Timezone identifier (added in PHP 5.1.0) //result.Append(zone.Id); //break; throw new NotImplementedException(); case 'D': // A textual representation of a day, three letters - Mon through Sun result.Append(local.ToString("ddd", DateTimeFormatInfo.InvariantInfo)); break; case 'F': // A full textual representation of a month, such as January or March - January through December result.Append(local.ToString("MMMM", DateTimeFormatInfo.InvariantInfo)); break; case 'g': // 12-hour format of an hour without leading zeros - 1 through 12 result.Append(local.ToString("%h", DateTimeFormatInfo.InvariantInfo)); break; case 'G': // 24-hour format of an hour without leading zeros - 0 through 23 result.Append(local.ToString("%H", DateTimeFormatInfo.InvariantInfo)); break; case 'h': // 12-hour format of an hour with leading zeros - 01 through 12 result.Append(local.ToString("hh", DateTimeFormatInfo.InvariantInfo)); break; case 'H': // 24-hour format of an hour with leading zeros - 00 through 23 result.Append(local.ToString("HH", DateTimeFormatInfo.InvariantInfo)); break; case 'i': // Minutes with leading zeros - 00 to 59 result.Append(local.ToString("mm", DateTimeFormatInfo.InvariantInfo)); break; case 'I': // Whether or not the date is in daylights savings time - 1 if Daylight Savings Time, 0 otherwise. result.Append(zone.IsDaylightSavingTime(local) ? "1" : "0"); break; case 'j': // Day of the month without leading zeros - 1 to 31 result.Append(local.ToString("%d", DateTimeFormatInfo.InvariantInfo)); break; case 'l': // A full textual representation of the day of the week - Sunday through Saturday result.Append(local.ToString("dddd", DateTimeFormatInfo.InvariantInfo)); break; case 'L': // Whether it's a leap year - 1 if it is a leap year, 0 otherwise. result.Append(System_DateTime.IsLeapYear(local.Year) ? "1" : "0"); break; case 'm': // Numeric representation of a month, with leading zeros - 01 through 12 result.Append(local.ToString("MM", DateTimeFormatInfo.InvariantInfo)); break; case 'M': // A short textual representation of a month, three letters - Jan through Dec result.Append(local.ToString("MMM", DateTimeFormatInfo.InvariantInfo)); break; case 'n': // Numeric representation of a month, without leading zeros - 1 through 12 result.Append(local.ToString("%M", DateTimeFormatInfo.InvariantInfo)); break; case 'N': // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) int day_of_week = (int)local.DayOfWeek; result.Append(day_of_week == 0 ? 7 : day_of_week); break; case 'o': { // ISO-8601 year number. This has the same value as Y, except that if the ISO // week number (W) belongs to the previous or next year, that year is used instead. // (added in PHP 5.1.0) int week, year; GetIsoWeekAndYear(local, out week, out year); result.Append(year); break; } case 'O': { // Difference to Greenwich time (GMT) in hours Example: +0200 TimeSpan offset = zone.GetUtcOffset(local); string sign = (offset.Ticks < 0) ? ((offset.Hours < 0) ? string.Empty : "-") : "+"; result.AppendFormat("{0}{1:00}{2:00}", sign, offset.Hours, offset.Minutes); break; } case 'P': { // same as 'O' but with the extra colon between hours and minutes // Difference to Greenwich time (GMT) in hours Example: +02:00 TimeSpan offset = zone.GetUtcOffset(local); string sign = (offset.Ticks < 0) ? ((offset.Hours < 0) ? string.Empty : "-") : "+"; result.AppendFormat("{0}{1:00}:{2:00}", sign, offset.Hours, offset.Minutes); break; } case 'r': // RFC 822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200 result.Append(local.ToString("ddd, dd MMM yyyy H:mm:ss ", DateTimeFormatInfo.InvariantInfo)); goto case 'O'; case 's': // Seconds, with leading zeros - 00 through 59 result.Append(local.ToString("ss", DateTimeFormatInfo.InvariantInfo)); break; case 'S': result.Append(GetDayNumberSuffix(local.Day)); break; case 't': // Number of days in the given month 28 through 31 result.Append(System_DateTime.DaysInMonth(local.Year, local.Month)); break; case 'T': // Timezone setting of this machine Examples: EST, MDT ... result.Append(zone.IsDaylightSavingTime(local) ? zone.DaylightName : zone.StandardName); break; case 'U': // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) result.Append(DateTimeUtils.UtcToUnixTimeStamp(utc)); break; case 'u': // Microseconds (added in PHP 5.2.2) result.Append((utc.Millisecond / 1000).ToString("D6")); break; case 'w': // Numeric representation of the day of the week - 0 (for Sunday) through 6 (for Saturday) result.Append((int)local.DayOfWeek); break; case 'W': { // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year) int week, year; GetIsoWeekAndYear(local, out week, out year); result.Append(week); break; } case 'y': // A two digit representation of a year Examples: 99 or 03 result.Append(local.ToString("yy", DateTimeFormatInfo.InvariantInfo)); break; case 'Y': // A full numeric representation of a year, 4 digits Examples: 1999 or 2003 result.Append(local.ToString("yyyy", DateTimeFormatInfo.InvariantInfo)); break; case 'z': // The day of the year starting from 0 result.Append(local.DayOfYear - 1); break; case 'Z': // TimeZone offset in seconds: result.Append((int)zone.GetUtcOffset(local).TotalSeconds); break; case '\\': // Escape char. Output next character directly to the result. escape = true; break; default: // unrecognized character, print it as-is. result.Append(ch); break; } } if (escape) { result.Append('\\'); } return(result.ToString()); }
private static int GetDatePart(char format, System_DateTime utc, TimeZoneInfo /*!*/ zone) { var local = TimeZoneInfo.ConvertTime(utc, zone);// zone.ToLocalTime(utc); switch (format) { case 'B': // Swatch Beat (Internet Time) - 000 through 999 return(GetSwatchBeat(utc)); case 'd': // Day of the month return(local.Day); case 'g': case 'h': // 12-hour format: return((local.Hour == 12) ? 12 : local.Hour % 12); case 'G': case 'H': // 24-hour format: return(local.Hour); case 'i': return(local.Minute); case 'I': return(zone.IsDaylightSavingTime(local) ? 1 : 0); case 'j': goto case 'd'; case 'L': return(System_DateTime.IsLeapYear(local.Year) ? 1 : 0); case 'm': return(local.Month); case 'n': goto case 'm'; case 's': return(local.Second); case 't': return(System_DateTime.DaysInMonth(local.Year, local.Month)); case 'U': return(DateTimeUtils.UtcToUnixTimeStamp(utc)); case 'w': // day of the week - 0 (for Sunday) through 6 (for Saturday) return((int)local.DayOfWeek); case 'W': { // ISO-8601 week number of year, weeks starting on Monday: int week, year; GetIsoWeekAndYear(local, out week, out year); return(week); } case 'y': return(local.Year % 100); case 'Y': return(local.Year); case 'z': return(local.DayOfYear - 1); case 'Z': return((int)zone.GetUtcOffset(local).TotalSeconds); default: //PhpException.InvalidArgument("format"); //return 0; throw new ArgumentException(); } }
public ScheduleController(Action<td, DateTime> ApplyStyle, DateTime date) { this.date = date; this.ApplyStyle = ApplyStyle; TotalPersentageStates = new[] { new ToggleButtonState { Percentage = 2 }, new ToggleButtonState { Percentage = 2.5 }, new ToggleButtonState { Percentage = 3 }, new ToggleButtonState { Percentage = 3.5 }, new ToggleButtonState { Percentage = 4 }, new ToggleButtonState { Percentage = 0 }, new ToggleButtonState { Percentage = 1 }, new ToggleButtonState { Percentage = 1.5 }, }; WorkerStates = new[] { new ToggleButtonState { Text = "·", Hours = 11.5, Percentage = 1 }, new ToggleButtonState { Text = "P", Hours = 0, Percentage = 0 }, new ToggleButtonState { Text = "17", Hours = 17 - 9.5, Percentage = 0.5 }, new ToggleButtonState { Text = "13", Hours = 21 - 13, Percentage = 0.5 }, }; days = date.DaysInMonth(); this.ScheduleTable.style.border = "1px solid gray"; this.ScheduleTable.border = 0; this.ScheduleTable.cellSpacing = 0; this.ScheduleTable.cellPadding = 0; this.Body = this.ScheduleTable.AddBody(); this.RowOfDateNumbers = this.Body.AddRow(); this.RowOfDayNames = this.Body.AddRow(); //Console.WriteLine(DateTime.Now + " step 2"); BuildTop(); //Console.WriteLine(DateTime.Now + " step 3"); BuildBottom(); //Console.WriteLine(DateTime.Now + " step 4"); Control.style.padding = "2em"; Header = new IHTMLElement(IHTMLElement.HTMLElementEnum.h2); Header.innerText = "work schedule".Localize(); var h4 = new IHTMLElement(IHTMLElement.HTMLElementEnum.h4); h4.style.Float = IStyle.FloatEnum.right; h4.innerText = date.Year + " / " + date.Month; var br = new IHTMLBreak(); br.style.clear = "both"; var close = new IHTMLAnchor("close!".Localize()); close.className = "noprint"; close.onclick += ev => { ev.PreventDefault(); this.Control.Dispose(); }; close.style.Float = IStyle.FloatEnum.right; var c = new IHTMLElement(IHTMLElement.HTMLElementEnum.center, close, Header, h4, br, this.ScheduleTable); c.AttachTo(this.Control); }
static List <DateTime> GetDates(string text) { //Stripping out all the spaces and new lines in the text //space separated dates text = Regex.Replace(text, @"\s+|\n+|((\r\n)+)", ""); const string months = @"January|February|March|April|May|June|July|August|September|October|November|December"; const string mons = @"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\.{0,1})"; var digit_date_patterns = new Dictionary <String, String> { { @"(19|20)\d{2}[\\\/\-\.]((0[1-9])|1(0|1|2)|[1-9])[\\\/\-\.](0[1-9]|(1|2)\d|3(0|1)|[1-9](?!(\d|\.)))", @"(?<year>(19|20)\d{2})[\\\/\-\.](?<month>((0[1-9])|1(0|1|2)|[1-9]))[\\\/\-\.](?<day>(0[1-9]|(1|2)\d|3(0|1)|[1-9]$))" }, { @"(0[1-9]|(1|2)\d|3(0|1)|(?<!(\d|\.))\d)[\\\/\-\.]((0[1-9])|1(0|1|2)|[1-9])[\\\/\-\.](19|20)\d{2}", @"(?<day>(0[1-9]|(1|2)\d|3(0|1)|^\d))[\\\/\-\.](?<month>((0[1-9])|1(0|1|2)|[1-9]))[\\\/\-\.](?<year>(19|20)\d{2})" } }; var mixed_date_patterns = new Dictionary <String, String> { { @"(?i)(19|20)\d{2}[\\\/\-\.]{0,1}(" + months + @"|" + mons + @")[\\\/\-\.]{0,1} (0[1-9]|(1|2)\d|3(0|1)|[1-9](?!(\d|\.)))", @"(?i)(?<year>(19|20)\d{2})[\\\/\-\.]{0,1}(?<month> (" + months + @"|" + mons + @"))[\\\/\-\.]{0,1}(?<day>(0[1-9]|(1|2)\d|3(0|1)|[1-9]$))" }, { @"(?i)(" + months + @"|" + mons + @")(0[1-9]|(1|2)\d|3(0|1)|[1-9])(st|nd|th){0,1}(\,){0,1}(19|20)\d{2}", @"(?i)(?<month>(" + months + @"|" + mons + @"))(?<day>(0[1-9]|(1|2)\d|3(0|1)|[1-9]))(st|nd|th){0,1}(\,){0,1}(?<year>(19|20)\d{2})" }, { @"(?i)(0[1-9]|(1|2)\d|3(0|1)|(?<!(\d|\.))\d)[\\\/\-\.]{0,1}(" + months + @"|" + mons + @")[\\\/\-\.]{0,1}(19|20)\d{2}", @"(?i)(?<day>(0[1-9]|(1|2)\d|3(0|1)|^\d))[\\\/\-\.]{0,1}(?<month>(" + months + @"|" + mons + @"))[\\\/\-\.]{0,1}(?<year>(19|20)\d{2})" }, { @"(?i)(0[1-9]|(1|2)\d|3(0|1)|(?<!(\d|\.))\d)(st|nd|th){0,1}(of|dayof){0,1}(" + months + @"|" + mons + @")(\,){0,1}(19|20)\d{2}", @"(?i)(?<day>(0[1-9]|(1|2)\d|3(0|1)|^\d))(st|nd|th){0,1}(of|dayof){0,1}(?<month>(" + months + @"|" + mons + @"))(\,){0,1}(?<year>(19|20)\d{2})" } }; var empty_day_patterns = new Dictionary <String, String> { { @"(?i)(" + months + @"|" + mons + @")(19|20)\d{2}", @"(?i)(?<month>(" + months + @"|" + mons + @"))(?<year>(19|20)\d{2})" }, { @"(?i)(19|20)\d{2}(" + months + @"|" + mons + @")", @"(?i)(?<year>(19|20)\d{2})(?<month>(" + months + @"|" + mons + @"))" } }; var partial_year_date_patterns = new Dictionary <String, String> { { @"(?<!(19|20))\d{2}[\\\/\-\.](0[1-9]|1(0|1|2)|[1-9])[\\\/\-\.](0[1-9]|(1|2)\d|3(0|1)|[1-9](?!(\d|\.)))", @"(?<year>\d{2})(?<separator1>[\\\/\-\.])(?<month>(0[1-9]|1(0|1|2)|[1-9]))(?<separator2>[\\\/\-\.])(?<day>(0[1-9]|(1|2)\d|3(0|1)|[1-9]$))" }, { @"(0[1-9]|(1|2)\d|3(0|1)|(?<!(\d|\.))\d)[\\\/\-\.]((0[1-9])|1(0|1|2)|[1-9])[\\\/\-\.]\d{2}(?!(\d\d))", @"(?<day>(0[1-9]|(1|2)\d|3(0|1)|^\d))(?<separator1>[\\\/\-\.])(?<month>((0[1-9])|1(0|1|2)|[1-9]))(?<separator2>[\\\/\-\.])(?<year>\d{2})" } }; var myDates = new List <DateTime?>(); var provider = CultureInfo.InstalledUICulture; foreach (var pattern in digit_date_patterns) { myDates = myDates.Concat(Regex.Matches(text, pattern.Key).Cast <Match>().Select(m => { var year = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${year}")); var month = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${month}")); var day = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${day}")); // Console.WriteLine("Date matched: " + m.Value); // Console.WriteLine("year: "+year+" || month: "+month+ " || day: "+day); return(new DateTime?(new DateTime(year, month, day))); }).ToList()).ToList().Distinct().ToList(); } foreach (var pattern in mixed_date_patterns) { //Add all occurrences of strings with the pattern to the result myDates = myDates.Concat(Regex.Matches(text, pattern.Key).Cast <Match>().Select(m => { // Console.WriteLine("Date matched: "+m.Value); var year = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${year}")); var monthMatched = Regex.Replace(m.Value, pattern.Value, @"${month}"); var day = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${day}")); // Console.WriteLine("year: "+year+" || month: "+monthMatched+ " || day: "+day); var month = DateTime.TryParseExact(monthMatched, new[] { "M", "MM", "MMM", "MMMM" }, provider, DateTimeStyles.None, out var dateTime) ? dateTime.Month : 1;; return(new DateTime?(new DateTime(year, month, day))); }).ToList()).ToList().Distinct().ToList(); } foreach (var pattern in empty_day_patterns) { myDates = myDates.Concat(Regex.Matches(text, pattern.Key).Cast <Match>().Select(m => { var year = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${year}")); var monthMatched = Regex.Replace(m.Value, pattern.Value, @"${month}"); // Console.WriteLine("Date matched: " + m.Value); // Console.WriteLine("year: "+year+" || month: "+monthMatched+ " || day: empty"); int month; int day; if (DateTime.TryParseExact(monthMatched, new[] { "M", "MM", "MMM", "MMMM" }, provider, DateTimeStyles.None, out var dateTime)) { month = dateTime.Month; day = DateTime.DaysInMonth(year, dateTime.Month); } else { month = 1; day = 1; }; return(new DateTime?(new DateTime(year, month, day))); }).ToList()).ToList().Distinct().ToList(); } if (partialYear) { foreach (var pattern in partial_year_date_patterns) { myDates = myDates.Concat(Regex.Matches(text, pattern.Key).Cast <Match>().Select(m => { var year = int.Parse(Regex.Replace(m.Value, pattern.Value, @"19${year}")); var month = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${month}")); var day = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${day}")); var sep1 = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${separator1}")); var sep2 = int.Parse(Regex.Replace(m.Value, pattern.Value, @"${separator2}")); if (day > DateTime.DaysInMonth(year, month)) { day = DateTime.DaysInMonth(year, month); } // Console.WriteLine("Date matched: "+m.Value); // Console.WriteLine("year: "+year+" || month: "+month+ " || day: "+day); return(sep1.Equals(sep2) ? new DateTime?(new DateTime(year, month, day)) : null); }).ToList()).ToList().Distinct().ToList(); } } var result = new List <DateTime>(); foreach (var myDate in myDates) { if (myDate.HasValue) { result.Add(myDate.Value); } } return(result.Distinct().OrderBy(x => x.Date).ToList()); }
protected static int GetLastDay(int year, int month, DayOfWeek dayOfWeek) => (from day in Enumerable.Range(1, DateObject.DaysInMonth(year, month)) where DateObject.MinValue.SafeCreateFromValue(year, month, day).DayOfWeek == dayOfWeek select day).Last();
protected DateTimeResolutionResult MatchWeekdayAndDay(string text, DateObject reference) { var ret = new DateTimeResolutionResult(); // Handling cases like 'Monday 21', which both 'Monday' and '21' refer to the same date. // The year of expected date can be different to the year of referenceDate. var match = this.config.WeekDayAndDayRegex.Match(text); if (match.Success) { int month = reference.Month, year = reference.Year; // Create a extract result which content ordinal string of text ExtractResult ertmp = new ExtractResult { Text = match.Groups["day"].Value, Start = match.Groups["day"].Index, Length = match.Groups["day"].Length, }; // Parse the day in text into number var day = ConvertCJKToNum(match.Groups["day"].Value); // Firstly, find a latest date with the "day" as pivotDate. // Secondly, if the pivotDate equals the referenced date, in other word, the day of the referenced date is exactly the "day". // In this way, check if the pivotDate is the weekday. If so, then the futureDate and the previousDate are the same date (referenced date). // Otherwise, increase the pivotDate month by month to find the latest futureDate and decrease the pivotDate month // by month to the latest previousDate. // Notice: if the "day" is larger than 28, some months should be ignored in the increase or decrease procedure. var pivotDate = new DateObject(year, month, 1); var daysInMonth = DateObject.DaysInMonth(year, month); if (daysInMonth >= day) { pivotDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { // Add 1 month is enough, since 1, 3, 5, 7, 8, 10, 12 months has 31 days pivotDate = pivotDate.AddMonths(1); pivotDate = DateObject.MinValue.SafeCreateFromValue(pivotDate.Year, pivotDate.Month, day); } var numWeekDayInt = (int)pivotDate.DayOfWeek; var extractedWeekDayStr = match.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[extractedWeekDayStr]; if (!pivotDate.Equals(DateObject.MinValue)) { if (numWeekDayInt == weekDay) { // The referenceDate is the weekday and with the "day". ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); } else { var futureDate = pivotDate; var pastDate = pivotDate; while ((int)futureDate.DayOfWeek != weekDay || futureDate.Day != day || futureDate < reference) { // Increase the futureDate month by month to find the expected date (the "day" is the weekday) and // make sure the futureDate not less than the referenceDate. futureDate = futureDate.AddMonths(1); var tmp = DateObject.DaysInMonth(futureDate.Year, futureDate.Month); if (tmp >= day) { // For months like January 31, after add 1 month, February 31 won't be returned, so the day should be revised ASAP. futureDate = futureDate.SafeCreateFromValue(futureDate.Year, futureDate.Month, day); } } ret.FutureValue = futureDate; while ((int)pastDate.DayOfWeek != weekDay || pastDate.Day != day || pastDate > reference) { // Decrease the pastDate month by month to find the expected date (the "day" is the weekday) and // make sure the pastDate not larger than the referenceDate. pastDate = pastDate.AddMonths(-1); var tmp = DateObject.DaysInMonth(pastDate.Year, pastDate.Month); if (tmp >= day) { // For months like March 31, after minus 1 month, February 31 won't be returned, so the day should be revised ASAP. pastDate = pastDate.SafeCreateFromValue(pastDate.Year, pastDate.Month, day); } } ret.PastValue = pastDate; if (weekDay == 0) { weekDay = 7; } ret.Timex = DateTimeFormatUtil.LuisDate(pastDate); } } ret.Success = true; return(ret); } return(ret); }
public void DaysInMonth_Returns_Valid_Result(DateTime date, int expectedResult) { Assert.That(date.DaysInMonth(), Is.EqualTo(expectedResult)); }
protected static int GetLastDay(int year, int month, DayOfWeek dayOfWeek) => (from day in Enumerable.Range(1, DateObject.DaysInMonth(year, month)) where new DateObject(year, month, day).DayOfWeek == dayOfWeek select day).Last();
/// <summary> /// /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateTime EndOfMonth(this DateTime date) { var days = DateTime.DaysInMonth(date.Year, date.Month); return(new DateTime(date.Year, date.Month, days).EndOfDay()); }
/// <summary> /// Sets the day of the <see cref="DateTime"/> to the last day in that month. /// </summary> /// <param name="current">The current DateTime to be changed.</param> /// <returns>given <see cref="DateTime"/> with the day part set to the last day in that month.</returns> public static DateTime LastDayOfMonth(this DateTime current) { return(current.SetDay(DateTime.DaysInMonth(current.Year, current.Month))); }
/// <summary> /// Returns all the days of a month. /// </summary> /// <param name="year">The year.</param> /// <param name="month">The month.</param> /// <returns></returns> public static IEnumerable <DateTime> DaysOfMonth(int year, int month) { return(Enumerable.Range(0, DateTime.DaysInMonth(year, month)) .Select(day => new DateTime(year, month, day + 1))); }