public void NextPrevFormatProperty() { DateTimeFormatInfo dateInfo = DateTimeFormatInfo.CurrentInfo; PokerCalendar c = new PokerCalendar(); StringWriter sw = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(sw); DateTime prevMonth = dateInfo.Calendar.AddMonths(DateTime.Today, -1); DateTime nextMonth = dateInfo.Calendar.AddMonths(DateTime.Today, 1); c.NextMonthText = "NextMonthText"; // CustomText c.PrevMonthText = "PrevMonthText"; c.RenderControl(tw); Assert.AreEqual(true, sw.ToString().IndexOf(c.NextMonthText) != -1, "NextPrevFormat1"); Assert.AreEqual(true, sw.ToString().IndexOf(c.PrevMonthText) != -1, "NextPrevFormat2"); sw = new StringWriter(); tw = new HtmlTextWriter(sw); c.NextPrevFormat = NextPrevFormat.FullMonth; // FullMonth c.RenderControl(tw); Assert.AreEqual(true, sw.ToString().IndexOf(dateInfo.GetMonthName(dateInfo.Calendar.GetMonth(prevMonth))) != -1, "NextPrevFormat3:" + sw.ToString() + "|||" + dateInfo.GetMonthName(DateTimeFormatInfo.CurrentInfo.Calendar.GetMonth(prevMonth))); Assert.AreEqual(true, sw.ToString().IndexOf(dateInfo.GetMonthName(dateInfo.Calendar.GetMonth(nextMonth))) != -1, "NextPrevFormat4"); sw = new StringWriter(); tw = new HtmlTextWriter(sw); c.NextPrevFormat = NextPrevFormat.ShortMonth; // ShortMonth c.RenderControl(tw); Assert.AreEqual(true, sw.ToString().IndexOf(dateInfo.GetAbbreviatedMonthName(dateInfo.Calendar.GetMonth(prevMonth))) != -1, "NextPrevFormat5"); Assert.AreEqual(true, sw.ToString().IndexOf(dateInfo.GetAbbreviatedMonthName(dateInfo.Calendar.GetMonth(nextMonth))) != -1, "NextPrevFormat6"); }
public static string GetMonthName(int Month) { DateTimeFormatInfo dfi = new DateTimeFormatInfo(); string monthName = dfi.GetAbbreviatedMonthName(Month); return(monthName); }
private void PerformPageSetup(TrainingDataEntities context) { DateTimeFormatInfo formatInfo = CultureInfo.CurrentCulture.DateTimeFormat; monthSelect.Items.Clear(); for (int i = 1; i < 13; i++) { monthSelect.Items.Add(formatInfo.GetAbbreviatedMonthName(i)); } // get the current date and use it to select a month and set the day and year DateTime now = DateTime.Now; monthSelect.SelectedIndex = now.Month - 1; dayInput.Value = now.Day.ToString(); yearInput.Value = now.Year.ToString(); // populate the athlete names athleteSelect.Items.Clear(); foreach (string name in DataAccess.GetAthleteNames(context)) { athleteSelect.Items.Add(name); } // populate the event types eventTypeSelect.Items.Clear(); foreach (string name in DataAccess.GetEventTypeNames(context)) { eventTypeSelect.Items.Add(name); } }
public void GetAbbreviatedMonthName(DateTimeFormatInfo info, string[] expected) { for (int i = MinMonth; i <= MaxMonth; ++i) { Assert.Equal(expected[i], info.GetAbbreviatedMonthName(i)); } }
/// <summary> /// Format <see cref="BirthDate.Month"/> and append the format-result to the <paramref name="result"/> /// and return the length of the token. /// </summary> /// <remarks> /// The formatted month will be: /// - If <see cref="BirthDateFormatInfo.MaskMonth"/> is true, masked with the same length as token, with /// <see cref="BirthDateFormatInfo.NumberMaskChar"/> (Token Length <= 2) or /// <see cref="BirthDateFormatInfo.TextMaskChar"/> (Token Length > 2). /// - Token length = 1: (Month mod 100) without leading zero. /// - Token length = 2: (Month mod 100) with leading zero. /// - Token length = 3: Month name abbreviated as 3 characters. /// - Token length > 3: Month name (not abbreviated). /// </remarks> /// <param name="result">The result.</param> /// <param name="format">The format.</param> /// <param name="pos">The position.</param> /// <param name="month">The month.</param> /// <returns></returns> private int FormatMonth(StringBuilder result, string format, int pos, int month) { int tokenLen = FormatHelper.ParseLengthOfRepeatPattern(format, pos, 'M'); if (tokenLen <= 2) { // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. FormatHelper.FormatDigits(result, month, tokenLen, _birthDateFormatInfo.MaskMonth, _birthDateFormatInfo.NumberMaskChar); } else if (tokenLen == 3 && !_birthDateFormatInfo.MaskMonth) { // tokenLen == 3 : Month as a three-letter abbreviation. result.Append(_dateTimeFormatInfo.GetAbbreviatedMonthName(month)); } else if (!_birthDateFormatInfo.MaskMonth) { // tokenLen >= 4 : Month as its full name. result.Append(_dateTimeFormatInfo.GetMonthName(month)); } else { result.Append("".PadLeft(tokenLen, _birthDateFormatInfo.TextMaskChar)); } return(tokenLen); }
static void Main(string[] args) { DateTimeFormatInfo dateTimeInfo = new DateTimeFormatInfo(); Console.Write(dateTimeInfo.GetAbbreviatedMonthName(4)); // Display April Console.ReadKey(); }
public void GetAbbreviatedMonthName_Invoke_ReturnsExpected(DateTimeFormatInfo info, string[] expected) { for (int i = MinMonth; i <= MaxMonth; ++i) { Assert.Equal(expected[i], info.GetAbbreviatedMonthName(i)); } }
private void VerificationHelper(DateTimeFormatInfo info, string[] expected) { for (int i = c_MIN_MONTH_VALUE; i <= c_MAX_MONTH_VALUE; ++i) { string actual = info.GetAbbreviatedMonthName(i); Assert.Equal(expected[i], actual); } }
// Token: 0x060015E1 RID: 5601 RVA: 0x0004058C File Offset: 0x0003E78C private static string FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { if (repeatCount == 3) { return(dtfi.GetAbbreviatedMonthName(month)); } return(dtfi.GetMonthName(month)); }
static void AnalyzeCategories ( int year, int month ) { string expression = string.Format ( CultureInfo.InvariantCulture, "RD={0:0000}{1:00}$", year, month ); int[] found = connection.Search(expression); List <MarcRecord> records = new BatchRecordReader ( connection, connection.Database, 500, true, found ) .ReadAll(true); ReaderInfo[] readers = records.Select(ReaderInfo.Parse).ToArray(); DictionaryCounterInt32 <string> counter = new DictionaryCounterInt32 <string>(); foreach (ReaderInfo reader in readers) { string category = reader.Category; if (!string.IsNullOrEmpty(category)) { counter.Increment(category); } } CultureInfo culture = CultureInfo.CurrentCulture; DateTimeFormatInfo format = culture.DateTimeFormat; Console.Write("{0} {1}", format.GetAbbreviatedMonthName(month), year); foreach (string category in knownCategories) { Console.Write("\t{0}", counter.GetValue(category)); } int others = 0; foreach (string key in counter.Keys) { if (!knownCategories.Contains(key)) { int value = counter[key]; others += value; } } Console.WriteLine("\t{0}", others); }
/// <summary> /// Returns the internationalised name of the month dependent on the setting of the 'Abbreviate' flag. /// </summary> /// <param name="month">The month number - 1 to 12.</param> /// <returns>The internationalised name of the month, short or long.</returns> private string GetMonthName(int month) { if (abbreviate) { return(dateTimeInfo.GetAbbreviatedMonthName(month)); } return(dateTimeInfo.GetMonthName(month)); }
public dynamic Eventstat() { DateTimeFormatInfo mn = new DateTimeFormatInfo(); var eve = this.GetAll(); var _event = eve.GroupBy(s => s.EventDate.Month).Select(s => new { mon = mn.GetAbbreviatedMonthName(s.Key), monval = s.Count() }).OrderBy(s => s.mon).ToList(); return(_event); }
public string formatDate(DateTime newStart) { string dayOfWeek = newStart.DayOfWeek.ToString(); string month = info.GetAbbreviatedMonthName(newStart.Month); string year = newStart.ToString("yyyy"); string day = newStart.Day.ToString("d"); return(dayOfWeek + ", " + month + ". " + formatDay(newStart) + ", " + year + " at " + formatTime(newStart)); }
public static string GetMonthName(int month, bool abbreviate, IFormatProvider provider) { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(provider); if (abbreviate) { return(info.GetAbbreviatedMonthName(month)); } return(info.GetMonthName(month)); }
private void GetMailboxHistory(ref CPDatabase database, DateTime current, ref DateTimeFormatInfo mfi, ref Dictionary <string, object> statistics) { // Get first day of month DateTime firstDay = new DateTime(current.Year, current.Month, 1); DateTime lastDay = new DateTime(current.Year, current.Month, DateTime.DaysInMonth(current.Year, current.Month)); var users = new int(); if (current.Year == DateTime.Today.Year && current.Month == DateTime.Today.Month) { // If we are doing todays month then we just count the total amount of mailboxes users = (from u in database.Users where u.MailboxPlan > 0 select u).Count(); } else { // Otherwise we are on other months and we need to look at statistics users = (from u in database.Stats_ExchCount where u.StatDate >= firstDay where u.StatDate <= lastDay orderby u.StatDate ascending select u.UserCount).FirstOrDefault(); } if (users < 1) { // If this is the very first point and it was null then we need to set it to zero so it will populate the whole graph if (firstDay < DateTime.Now.AddMonths(-11)) { statistics.Add(string.Format("{0} {1}", mfi.GetAbbreviatedMonthName(current.Month), current.Year), 0); } else { statistics.Add(string.Format("{0} {1}", mfi.GetAbbreviatedMonthName(current.Month), current.Year), null); } } else { statistics.Add(string.Format("{0} {1}", mfi.GetAbbreviatedMonthName(current.Month), current.Year), users); } }
/// <summary> /// Gets the abbreviated or full month name for the specified <paramref name="month"/> and <paramref name="year"/> value, /// using the <paramref name="nameProvider"/> if not null or the <see cref="DateTimeFormatInfo"/> specified by <paramref name="info"/>. /// </summary> /// <param name="month">The month value to get the month name for.</param> /// <param name="year">The year value to get the month name for.</param> /// <param name="info">The <see cref="DateTimeFormatInfo"/> value to use.</param> /// <param name="nameProvider">The <see cref="ICustomFormatProvider"/> to get the name. /// This parameter has precedence before the <paramref name="info"/>. Can be <c>null</c>.</param> /// <param name="abbreviated">true to get the abbreviated month name; false otherwise.</param> /// <returns>The full or abbreviated month name specified by <paramref name="month"/> and <paramref name="year"/>.</returns> private static string GetMonthName(int month, int year, DateTimeFormatInfo info, ICustomFormatProvider nameProvider, bool abbreviated) { if (nameProvider != null) { return(abbreviated ? nameProvider.GetAbbreviatedMonthName(year, month) : nameProvider.GetMonthName(year, month)); } return(abbreviated ? info.GetAbbreviatedMonthName(month) : info.GetMonthName(month)); }
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { Contract.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return(dtfi.GetAbbreviatedMonthName(month)); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return(dtfi.GetMonthName(month)); }
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { if (!dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time)) && (month >= 7)) { month++; } if (repeatCount == 3) { return(dtfi.GetAbbreviatedMonthName(month)); } return(dtfi.GetMonthName(month)); }
public string ExportSummaryToExcel() { // string level = "Horizontal"; string vertical; string country; DateTimeFormatInfo dt = new DateTimeFormatInfo(); string abbMonth = dt.GetAbbreviatedMonthName(DateTime.Now.Month); string date = DateTime.Now.Day.ToString(); string fileName = AppSettings.RevenueLossReportFileName + abbMonth + "_" + date + ".xlsx"; ExcelPackage pack = CreateExcel(fileName); CreateWorksheets(pack); country = null; vertical = null; GetOverallRevLossSummary(vertical, pack); GetOverallRevLossSummary("TD", pack); GetOverallRevLossSummary("RBC", pack); GetOverallRevLossSummary("Scotia", pack); GetOverallRevLossSummary("CIBC", pack); GetOverallRevLossSummary("BMO", pack); GetAccountRevLossSummary("TD", "Canada", pack); GetAccountRevLossSummary("RBC", "Canada", pack); GetAccountRevLossSummary("Scotia", "Canada", pack); GetAccountRevLossSummary("CIBC", "Canada", pack); GetAccountRevLossSummary("BMO", "Canada", pack); GetAccountRevLossSummary("TD", "US", pack); GetAccountRevLossSummary("RBC", "US", pack); GetAccountRevLossSummary("RBC", "UK", pack); GetOverallPositionSummary("Horizontal", vertical, pack); GetOverallPositionSummary("Vertical", vertical, pack); GetOverallPositionSummary("Horizontal", "TD", pack); GetOverallPositionSummary("Horizontal", "RBC", pack); GetOverallPositionSummary("Horizontal", "Scotia", pack); GetOverallPositionSummary("Horizontal", "CIBC", pack); GetOverallPositionSummary("Horizontal", "BMO", pack); GetAccountPositionsSummary("TD", "Canada", pack); GetAccountPositionsSummary("TD", "US", pack); GetAccountPositionsSummary("RBC", "Canada", pack); GetAccountPositionsSummary("RBC", "US", pack); GetAccountPositionsSummary("RBC", "UK", pack); GetAccountPositionsSummary("Scotia", country, pack); GetAccountPositionsSummary("CIBC", country, pack); GetAccountPositionsSummary("BMO", country, pack); pack.Save(); return(fileName); }
protected void Page_Load(object sender, EventArgs e) { if (!User.Identity.IsAuthenticated) Server.Transfer("Login.aspx?redirect=UserProfile.aspx"); else { ((HtmlGenericControl)Master.FindControl("profile")).Attributes.Add("class", "current_page_item"); if (!IsPostBack) { /*populate birth date dropdownlists*/ //day Day_DropDownList.Items.Add(new ListItem("--Day--", "0")); for (int day = 1; day <= 31; day++) Day_DropDownList.Items.Add(new ListItem(day.ToString(), day.ToString())); //month DateTimeFormatInfo dtf = new DateTimeFormatInfo(); Month_DropDownList.Items.Add(new ListItem("--Month--", "0")); for (int month = 1; month <= 12; month++) Month_DropDownList.Items.Add(new ListItem(dtf.GetAbbreviatedMonthName(month).ToString(), month.ToString())); //year int currYear = DateTime.Now.Year; Year_DropDownList.Items.Add(new ListItem("--Year--", "0")); for (int year = 1; year <= 50; year++) Year_DropDownList.Items.Add(new ListItem((currYear - year + 1).ToString(), year.ToString())); /*populate birth date dropdownlists*/ /*populate with user details if any*/ UserExtraInfo info = DataBaseManager.GetUserExtraInfo(((Guid)(Membership.GetUser().ProviderUserKey)).ToString()); if (info != null) { Name_TextBox.Text = info.RealName; Gender_RadioButtonList.SelectedIndex = Convert.ToInt32(info.Gender); if (currYear - 50 < info.BirthDate.Year && info.BirthDate.Year <= currYear) { Day_DropDownList.SelectedIndex = info.BirthDate.Day; Month_DropDownList.SelectedIndex = info.BirthDate.Month; Year_DropDownList.SelectedIndex = currYear - info.BirthDate.Year + 1; } Country_TextBox.Text = info.Country; City_TextBox.Text = info.City; Description_TextBox.Text = info.Description; } else Gender_RadioButtonList.SelectedIndex = 0; /*populate with user details if any*/ } } }
public override string ToString() //This ToString is returned specifically when checking what campsites exist at a specific campground { DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); string campgroundString = "# ".PadLeft(5) + $"{Campground_id}".PadRight(20) + $"{Name}".PadRight(41) + $"{dtfi.GetAbbreviatedMonthName(Open_from_mm)}".PadRight(4) + "-".PadRight(2) + $"{dtfi.GetAbbreviatedMonthName(Open_to_mm)}".PadRight(20).PadLeft(3) + $"{Daily_fee:C}"; return(campgroundString); }
private void Button1_Click(object sender, EventArgs e) { DateTimeFormatInfo mfi = new DateTimeFormatInfo(); DateTime dt = DateTime.Now; int year = dt.Year; int col1 = dt.AddMonths(-5).Month; int col2 = dt.AddMonths(-4).Month; int col3 = dt.AddMonths(-3).Month; int col4 = dt.AddMonths(-2).Month; int col5 = dt.AddMonths(-1).Month; int col6 = dt.Month; int[] col = new int[6] { dt.AddMonths(-5).Month, dt.AddMonths(-4).Month, dt.AddMonths(-3).Month, dt.AddMonths(-2).Month, dt.AddMonths(-1).Month, dt.Month }; for (int i = 0; i < col.Length; i++) { string strMonthName = mfi.GetAbbreviatedMonthName(col[i]); string query = " select sum(quantity) from productsales where productname='" + cbItem.Text + "' and year(datetime)= '" + year + "' and month(datetime)= '" + col[i] + "'"; string query1 = "select sum(quantity) from productsales where year(datetime)= '" + year + "' and month(datetime)= '" + col[i] + "'"; MySqlCommand command = new MySqlCommand(query, connection); connection.Open(); MySqlDataReader r = command.ExecuteReader(); try { r.Read(); int item_quantity = Convert.ToInt32(r[0]); this.chart1.Series["Total sales of an Item monthly"].Points.AddXY(strMonthName, r[0]); connection.Close(); MySqlCommand command1 = new MySqlCommand(query1, connection); connection.Open(); MySqlDataReader r1 = command1.ExecuteReader(); while (r1.Read()) { int total_quantity = Convert.ToInt32(r1[0]); double rate = (total_quantity / item_quantity); double rate_an_item = (1 / rate) * 100; this.chart1.Series["Rate of an item monthly"].Points.AddXY(strMonthName, rate_an_item); } }catch (Exception ee) { MessageBox.Show(ee.Message, "Invalid!"); } connection.Close(); } }
public static string[] getShortMonths(string langTag, string[] smonths) { CultureInfo ci; if (TryGetCultureInfoFromLangTag(langTag, out ci)) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; for (int i = 1; i <= 13; i++) { smonths[i - 1] = dtfi.GetAbbreviatedMonthName(i); } } return(smonths); }
/// <summary> /// Formats the date without the milliseconds part /// </summary> /// <param name="dateToFormat">The date to format.</param> /// <param name="buffer">The string builder to write to.</param> /// <remarks> /// <para> /// Formats a DateTime in the format <c>"dd MMM yyyy HH:mm:ss"</c> /// for example, <c>"06 Nov 1994 15:49:37"</c>. /// </para> /// <para> /// The base class will append the <c>",fff"</c> milliseconds section. /// This method will only be called at most once per second. /// </para> /// </remarks> protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) { int day = dateToFormat.Day; if (day < 10) { buffer.Append('0'); } buffer.Append(day); buffer.Append(' '); buffer.Append(m_dateTimeFormatInfo.GetAbbreviatedMonthName(dateToFormat.Month)); buffer.Append(' '); buffer.Append(dateToFormat.Year); buffer.Append(' '); base.FormatDateWithoutMillis(dateToFormat, buffer); }
// Token: 0x060015E2 RID: 5602 RVA: 0x000405A4 File Offset: 0x0003E7A4 private static string FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { return(dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, repeatCount == 3)); } if (month >= 7) { month++; } if (repeatCount == 3) { return(dtfi.GetAbbreviatedMonthName(month)); } return(dtfi.GetMonthName(month)); }
public void TestInvalidDayOfWeek() { DateTimeFormatInfo info1 = new DateTimeFormatInfo(); Assert.Throws <ArgumentOutOfRangeException>(() => { info1.GetAbbreviatedMonthName(c_MIN_MONTH_VALUE - 1); }); DateTimeFormatInfo info2 = new DateTimeFormatInfo(); Assert.Throws <ArgumentOutOfRangeException>(() => { info2.GetAbbreviatedMonthName(c_MAX_MONTH_VALUE + 1); }); }
private bool VerificationHelper(DateTimeFormatInfo info, string[] expected, string errorno) { bool retval = true; for (int i = c_MIN_MONTH_VALUE; i <= c_MAX_MONTH_VALUE; ++i) { string actual = info.GetAbbreviatedMonthName(i); if (actual != expected[i]) { TestLibrary.TestFramework.LogError(errorno, "GetAbbreviatedDayName returns wrong value"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] i = " + i + ", expected[i] = " + expected[i] + ", actual = " + actual); retval = false; } } return(retval); }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. "); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MIN_MONTH_VALUE - 1); TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MAX_MONTH_VALUE + 1); TestLibrary.TestFramework.LogError("101.3", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.4", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return(retVal); }
/* * Constructor which initialises the entries of the waiting list items listview. */ public SingleWaitingListItemPage(WaitingListItem waitingListItem, Boolean showDeregisterButton) { InitializeComponent(); Title = "Waiting list item"; this.item = waitingListItem; OrganTypeEntry.Text = OrganExtensions.ToString(waitingListItem.organType); RegisteredDateEntry.Text = waitingListItem.organRegisteredDate.day + " of " + dateTimeFormat.GetAbbreviatedMonthName(waitingListItem.organRegisteredDate.month) + ", " + waitingListItem.organRegisteredDate.year; DeregisteredDateEntry.Text = waitingListItem.organDeregisteredDate != null ? waitingListItem.organDeregisteredDate.day + " of " + dateTimeFormat.GetAbbreviatedMonthName(waitingListItem.organDeregisteredDate.month) + ", " + waitingListItem.organDeregisteredDate.year : "N/A"; //DeregisterCodeEntry.Text = //waitingListItem.OrganDeregisteredCode != 0 ? waitingListItem.OrganDeregisteredCode.ToString() : "N/A"; DeregisterButton.IsVisible = showDeregisterButton; IDEntry.Text = waitingListItem.id.ToString(); }
// // FormatHebrewMonthName // // Action: Return the Hebrew month name for the specified DateTime. // Returns: The month name string for the specified DateTime. // Arguments: // time the time to format // month The month is the value of HebrewCalendar.GetMonth(time). // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. // Exceptions: None. // /* Note: * If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: * 1 Hebrew 1st Month * 2 Hebrew 2nd Month * .. ... * 6 Hebrew 6th Month * 7 Hebrew 6th Month II (used only in a leap year) * 8 Hebrew 7th Month * 9 Hebrew 8th Month * 10 Hebrew 9th Month * 11 Hebrew 10th Month * 12 Hebrew 11th Month * 13 Hebrew 12th Month * * Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7. */ private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return(dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3))); } // This is in a regular year. if (month >= 7) { month++; } if (repeatCount == 3) { return(dtfi.GetAbbreviatedMonthName(month)); } return(dtfi.GetMonthName(month)); }
string GetNextPrevFormatText(DateTime date, bool next) { string text; DateTimeFormatInfo dti = DateInfo; switch (NextPrevFormat) { case NextPrevFormat.FullMonth: text = dti.GetMonthName(GetGlobalCalendar().GetMonth(date)); break; case NextPrevFormat.ShortMonth: text = dti.GetAbbreviatedMonthName(GetGlobalCalendar().GetMonth(date)); break; case NextPrevFormat.CustomText: default: text = ((next) ? NextMonthText : PrevMonthText); break; } return(text); }
public static string ToString(DateTime dt, TimeSpan?utc_offset, string format, DateTimeFormatInfo dfi) { // the length of the format is usually a good guess of the number // of chars in the result. Might save us a few bytes sometimes // Add + 10 for cases like mmmm dddd StringBuilder result = new StringBuilder(format.Length + 10); // For some cases, the output should not use culture dependent calendar DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo; if (format == inv.RFC1123Pattern) { dfi = inv; } else if (format == inv.UniversalSortableDateTimePattern) { dfi = inv; } int i = 0; while (i < format.Length) { int tokLen; bool omitZeros = false; char ch = format [i]; switch (ch) { // // Time Formats // case 'h': // hour, [1, 12] tokLen = DateTimeUtils.CountRepeat(format, i, ch); int hr = dt.Hour % 12; if (hr == 0) { hr = 12; } DateTimeUtils.ZeroPad(result, hr, tokLen == 1 ? 1 : 2); break; case 'H': // hour, [0, 23] tokLen = DateTimeUtils.CountRepeat(format, i, ch); DateTimeUtils.ZeroPad(result, dt.Hour, tokLen == 1 ? 1 : 2); break; case 'm': // minute, [0, 59] tokLen = DateTimeUtils.CountRepeat(format, i, ch); DateTimeUtils.ZeroPad(result, dt.Minute, tokLen == 1 ? 1 : 2); break; case 's': // second [0, 29] tokLen = DateTimeUtils.CountRepeat(format, i, ch); DateTimeUtils.ZeroPad(result, dt.Second, tokLen == 1 ? 1 : 2); break; case 'F': omitZeros = true; goto case 'f'; case 'f': // fraction of second, to same number of // digits as there are f's tokLen = DateTimeUtils.CountRepeat(format, i, ch); if (tokLen > 7) { throw new FormatException("Invalid Format String"); } int dec = (int)((long)(dt.Ticks % TimeSpan.TicksPerSecond) / (long)Math.Pow(10, 7 - tokLen)); int startLen = result.Length; DateTimeUtils.ZeroPad(result, dec, tokLen); if (omitZeros) { while (result.Length > startLen && result [result.Length - 1] == '0') { result.Length--; } // when the value was 0, then trim even preceding '.' (!) It is fixed character. if (dec == 0 && startLen > 0 && result [startLen - 1] == '.') { result.Length--; } } break; case 't': // AM/PM. t == first char, tt+ == full tokLen = DateTimeUtils.CountRepeat(format, i, ch); string desig = dt.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator; if (tokLen == 1) { if (desig.Length >= 1) { result.Append(desig [0]); } } else { result.Append(desig); } break; case 'z': // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm tokLen = DateTimeUtils.CountRepeat(format, i, ch); TimeSpan offset = utc_offset ?? TimeZone.CurrentTimeZone.GetUtcOffset(dt); if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); } switch (tokLen) { case 1: result.Append(Math.Abs(offset.Hours)); break; case 2: result.Append(Math.Abs(offset.Hours).ToString("00")); break; default: result.Append(Math.Abs(offset.Hours).ToString("00")); result.Append(':'); result.Append(Math.Abs(offset.Minutes).ToString("00")); break; } break; case 'K': // 'Z' (UTC) or zzz (Local) tokLen = 1; if (utc_offset != null || dt.Kind == DateTimeKind.Local) { offset = utc_offset ?? TimeZone.CurrentTimeZone.GetUtcOffset(dt); if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); } result.Append(Math.Abs(offset.Hours).ToString("00")); result.Append(':'); result.Append(Math.Abs(offset.Minutes).ToString("00")); } else if (dt.Kind == DateTimeKind.Utc) { result.Append('Z'); } break; // // Date tokens // case 'd': // day. d(d?) = day of month (leading 0 if two d's) // ddd = three leter day of week // dddd+ full day-of-week tokLen = DateTimeUtils.CountRepeat(format, i, ch); if (tokLen <= 2) { DateTimeUtils.ZeroPad(result, dfi.Calendar.GetDayOfMonth(dt), tokLen == 1 ? 1 : 2); } else if (tokLen == 3) { result.Append(dfi.GetAbbreviatedDayName(dfi.Calendar.GetDayOfWeek(dt))); } else { result.Append(dfi.GetDayName(dfi.Calendar.GetDayOfWeek(dt))); } break; case 'M': // Month.m(m?) = month # (with leading 0 if two mm) // mmm = 3 letter name // mmmm+ = full name tokLen = DateTimeUtils.CountRepeat(format, i, ch); int month = dfi.Calendar.GetMonth(dt); if (tokLen <= 2) { DateTimeUtils.ZeroPad(result, month, tokLen); } else if (tokLen == 3) { result.Append(dfi.GetAbbreviatedMonthName(month)); } else { result.Append(dfi.GetMonthName(month)); } break; case 'y': // Year. y(y?) = two digit year, with leading 0 if yy // yyy+ full year with leading zeros if needed. tokLen = DateTimeUtils.CountRepeat(format, i, ch); if (tokLen <= 2) { DateTimeUtils.ZeroPad(result, dfi.Calendar.GetYear(dt) % 100, tokLen); } else { DateTimeUtils.ZeroPad(result, dfi.Calendar.GetYear(dt), tokLen); } break; case 'g': // Era name tokLen = DateTimeUtils.CountRepeat(format, i, ch); result.Append(dfi.GetEraName(dfi.Calendar.GetEra(dt))); break; // // Other // case ':': result.Append(dfi.TimeSeparator); tokLen = 1; break; case '/': result.Append(dfi.DateSeparator); tokLen = 1; break; case '\'': case '"': tokLen = DateTimeUtils.ParseQuotedString(format, i, result); break; case '%': if (i >= format.Length - 1) { throw new FormatException("% at end of date time string"); } if (format [i + 1] == '%') { throw new FormatException("%% in date string"); } // Look for the next char tokLen = 1; break; case '\\': // C-Style escape if (i >= format.Length - 1) { throw new FormatException("\\ at end of date time string"); } result.Append(format [i + 1]); tokLen = 2; break; default: // catch all result.Append(ch); tokLen = 1; break; } i += tokLen; } return(result.ToString()); }
public void TestInvalidDayOfWeek() { DateTimeFormatInfo info1 = new DateTimeFormatInfo(); Assert.Throws<ArgumentOutOfRangeException>(() => { info1.GetAbbreviatedMonthName(c_MIN_MONTH_VALUE - 1); }); DateTimeFormatInfo info2 = new DateTimeFormatInfo(); Assert.Throws<ArgumentOutOfRangeException>(() => { info2.GetAbbreviatedMonthName(c_MAX_MONTH_VALUE + 1); }); }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. "); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MIN_MONTH_VALUE - 1); TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MAX_MONTH_VALUE + 1); TestLibrary.TestFramework.LogError("101.3", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.4", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
private bool VerificationHelper(DateTimeFormatInfo info, string[] expected, string errorno) { bool retval = true; for (int i = c_MIN_MONTH_VALUE; i <= c_MAX_MONTH_VALUE; ++i) { string actual = info.GetAbbreviatedMonthName(i); if (actual != expected[i]) { TestLibrary.TestFramework.LogError(errorno, "GetAbbreviatedDayName returns wrong value"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] i = " + i + ", expected[i] = " + expected[i] + ", actual = " + actual); retval = false; } } return retval; }