public void EraName() { CultureInfo en_US = new CultureInfo("en-US"); DateTimeFormatInfo dtfi = en_US.DateTimeFormat; Assert.AreEqual("AD", dtfi.GetAbbreviatedEraName(0), "#1"); Assert.AreEqual("AD", dtfi.GetAbbreviatedEraName(1), "#7"); Assert.AreEqual("A.D.", dtfi.GetEraName(0), "#8"); Assert.AreEqual("A.D.", dtfi.GetEraName(1), "#2"); Assert.AreEqual(1, dtfi.GetEra("A.D."), "#3"); Assert.AreEqual(1, dtfi.GetEra("AD"), "#4"); Assert.AreEqual(-1, dtfi.GetEra("C.E"), "#5"); Assert.AreEqual(-1, dtfi.GetEra("Common Era"), "#6"); }
private string GetTodayDate(int calendarIndex) { StringBuilder stringBuilder = new StringBuilder(150); _today = DateTime.Today; Calendar calendar = CalendarStatics.CalendarsInfo[calendarIndex].Calendar; DateTimeFormatInfo format = CalendarStatics.CalendarsInfo[calendarIndex].Format; string calendarName = CalendarStatics.GetCalendarName(CalendarStatics.CalendarsInfo[calendarIndex].Calendar); stringBuilder.Append(" "); stringBuilder.Append(calendarName); stringBuilder.Append(": "); if (CalendarStatics.CalendarsInfo[calendarIndex].IsCompatibleCalendar) { stringBuilder.Append(_today.ToString("D", format)); stringBuilder.Append(_today.ToString(" gg", format)); } else { stringBuilder.Append(calendar.GetMonth(_today).ToString(CultureInfo.InvariantCulture)); stringBuilder.Append("/"); stringBuilder.Append(calendar.GetDayOfMonth(_today).ToString(CultureInfo.InvariantCulture)); stringBuilder.Append("/"); stringBuilder.Append(calendar.GetYear(_today).ToString(CultureInfo.InvariantCulture)); stringBuilder.Append(" "); stringBuilder.Append(format.GetEraName(calendar.GetEra(_today))); } return(stringBuilder.ToString()); }
public static string GetStaticDisplayText(SpecifierInfo specifier, DateTimeFormatInfo dateTimeFormat, Calendar calendar, DateTime?value) { if (specifier.ValueType != ValueType.Static) { throw new ArgumentException("specifier"); } switch (specifier.Type) { case SpecifierType.g: if (value.HasValue) { int era = calendar.GetEra(value.Value); return(dateTimeFormat.GetEraName(era)); } return(string.Empty); case SpecifierType.DateSeparator: return(dateTimeFormat.DateSeparator); case SpecifierType.TimeSeparator: return(dateTimeFormat.TimeSeparator); default: throw new ArgumentOutOfRangeException("specifier.Type"); } }
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.OnPreRender"]/*' /> public override void OnPreRender(EventArgs e) { base.OnPreRender(e); // We specially binding eras of the current calendar object here // when the UI of typing date is display. We do it only if the // calendar supports more than one era. if (SecondaryUIMode == TypeDate) { DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo; int [] ints = currentInfo.Calendar.Eras; if (ints.Length > 1) { // Save the value in private view state _eraCount = ints.Length; int currentEra; if (_selectList.SelectedIndex != -1) { currentEra = ints[_selectList.SelectedIndex]; } else { currentEra = currentInfo.Calendar.GetEra(Control.VisibleDate); } // Clear the placeholder item list if created in LoadAdapterState _selectList.Items.Clear(); for (int i = 0; i < ints.Length; i++) { int era = ints[i]; _selectList.Items.Add(currentInfo.GetEraName(era)); // There is no association between the era value and // its index in the era array, so we need to check it // explicitly for the default selected index. if (currentEra == era) { _selectList.SelectedIndex = i; } } _selectList.Visible = true; } else { // disable viewstate since no need to save any data for // this control _selectList.EnableViewState = false; } } else { _selectList.EnableViewState = false; } }
// Parse an era name. private static int ParseEra(String s, ref int posn, Calendar calendar, DateTimeFormatInfo info) { // Get the list of eras from the calendar. int[] eras = calendar.Eras; // Convert the eras into era names. String[] eraNames = new String [eras.Length]; int index; for (index = 0; index < eras.Length; ++index) { eraNames[index] = info.GetEraName(eras[index]); } // Parse the era value using the strings we just got. return(ParseOneOf(s, ref posn, eraNames)); }
private static string FormatCustomized(DateTime dateTime, string format, DateTimeFormatInfo dtfi, TimeSpan offset) { int num2; Calendar calendar = dtfi.Calendar; StringBuilder outputBuffer = new StringBuilder(); bool flag = calendar.ID == 8; bool timeOnly = true; for (int i = 0; i < format.Length; i += num2) { int num4; int dayOfMonth; int num8; int month; int year; char patternChar = format[i]; switch (patternChar) { case 'F': case 'f': break; case 'H': { num2 = ParseRepeatPattern(format, i, patternChar); FormatDigits(outputBuffer, dateTime.Hour, num2); continue; } case ':': { outputBuffer.Append(dtfi.TimeSeparator); num2 = 1; continue; } case '/': { outputBuffer.Append(dtfi.DateSeparator); num2 = 1; continue; } case '%': { num4 = ParseNextChar(format, i); if ((num4 < 0) || (num4 == 0x25)) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } char ch3 = (char)num4; outputBuffer.Append(FormatCustomized(dateTime, ch3.ToString(), dtfi, offset)); num2 = 2; continue; } case '\'': case '"': { StringBuilder result = new StringBuilder(); num2 = ParseQuoteString(format, i, result); outputBuffer.Append(result); continue; } case 'K': { num2 = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, outputBuffer); continue; } case 'M': num2 = ParseRepeatPattern(format, i, patternChar); month = calendar.GetMonth(dateTime); if (num2 > 2) { goto Label_03D3; } if (!flag) { goto Label_03C7; } HebrewFormatDigits(outputBuffer, month); goto Label_042E; case '\\': { num4 = ParseNextChar(format, i); if (num4 < 0) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } outputBuffer.Append((char)num4); num2 = 2; continue; } case 'd': num2 = ParseRepeatPattern(format, i, patternChar); if (num2 > 2) { goto Label_037F; } dayOfMonth = calendar.GetDayOfMonth(dateTime); if (!flag) { goto Label_0373; } HebrewFormatDigits(outputBuffer, dayOfMonth); goto Label_0399; case 'g': { num2 = ParseRepeatPattern(format, i, patternChar); outputBuffer.Append(dtfi.GetEraName(calendar.GetEra(dateTime))); continue; } case 'h': { num2 = ParseRepeatPattern(format, i, patternChar); int num3 = dateTime.Hour % 12; if (num3 == 0) { num3 = 12; } FormatDigits(outputBuffer, num3, num2); continue; } case 's': { num2 = ParseRepeatPattern(format, i, patternChar); FormatDigits(outputBuffer, dateTime.Second, num2); continue; } case 't': { num2 = ParseRepeatPattern(format, i, patternChar); if (num2 != 1) { goto Label_0327; } if (dateTime.Hour >= 12) { goto Label_02FE; } if (dtfi.AMDesignator.Length >= 1) { outputBuffer.Append(dtfi.AMDesignator[0]); } continue; } case 'm': { num2 = ParseRepeatPattern(format, i, patternChar); FormatDigits(outputBuffer, dateTime.Minute, num2); continue; } case 'y': year = calendar.GetYear(dateTime); num2 = ParseRepeatPattern(format, i, patternChar); if (!dtfi.HasForceTwoDigitYears) { goto Label_0466; } FormatDigits(outputBuffer, year, (num2 <= 2) ? num2 : 2); goto Label_04B5; case 'z': { num2 = ParseRepeatPattern(format, i, patternChar); FormatCustomizedTimeZone(dateTime, offset, format, num2, timeOnly, outputBuffer); continue; } default: goto Label_05A4; } num2 = ParseRepeatPattern(format, i, patternChar); if (num2 > 7) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } long num5 = dateTime.Ticks % 0x989680L; num5 /= (long)Math.Pow(10.0, (double)(7 - num2)); if (patternChar == 'f') { outputBuffer.Append(((int)num5).ToString(fixedNumberFormats[num2 - 1], CultureInfo.InvariantCulture)); continue; } int num6 = num2; while (num6 > 0) { if ((num5 % 10L) != 0L) { break; } num5 /= 10L; num6--; } if (num6 > 0) { outputBuffer.Append(((int)num5).ToString(fixedNumberFormats[num6 - 1], CultureInfo.InvariantCulture)); } else if ((outputBuffer.Length > 0) && (outputBuffer[outputBuffer.Length - 1] == '.')) { outputBuffer.Remove(outputBuffer.Length - 1, 1); } continue; Label_02FE: if (dtfi.PMDesignator.Length >= 1) { outputBuffer.Append(dtfi.PMDesignator[0]); } continue; Label_0327: outputBuffer.Append((dateTime.Hour < 12) ? dtfi.AMDesignator : dtfi.PMDesignator); continue; Label_0373: FormatDigits(outputBuffer, dayOfMonth, num2); goto Label_0399; Label_037F: num8 = (int)calendar.GetDayOfWeek(dateTime); outputBuffer.Append(FormatDayOfWeek(num8, num2, dtfi)); Label_0399: timeOnly = false; continue; Label_03C7: FormatDigits(outputBuffer, month, num2); goto Label_042E; Label_03D3: if (flag) { outputBuffer.Append(FormatHebrewMonthName(dateTime, month, num2, dtfi)); } else if (((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != DateTimeFormatFlags.None) && (num2 >= 4)) { outputBuffer.Append(dtfi.internalGetMonthName(month, IsUseGenitiveForm(format, i, num2, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false)); } else { outputBuffer.Append(FormatMonth(month, num2, dtfi)); } Label_042E: timeOnly = false; continue; Label_0466: if (calendar.ID == 8) { HebrewFormatDigits(outputBuffer, year); } else if (num2 <= 2) { FormatDigits(outputBuffer, year % 100, num2); } else { string str = "D" + num2; outputBuffer.Append(year.ToString(str, CultureInfo.InvariantCulture)); } Label_04B5: timeOnly = false; continue; Label_05A4: outputBuffer.Append(patternChar); num2 = 1; } return(outputBuffer.ToString()); }
public void GetEraName(DateTimeFormatInfo format, int era, string expected) { Assert.Equal(expected, format.GetEraName(era)); }
/// <summary> /// Returns a string representation of this object. /// </summary> /// <param name="format">The format pattern.</param> /// <param name="dtfi">The <see cref="DateTimeFormatInfo"/> to use for formatting.</param> /// <param name="nameProvider">The day and month name provider.</param> /// <param name="nativeDigits">If not <c>null</c> and valid, uses for number representation the specified native digits.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> private string ToString(string format, DateTimeFormatInfo dtfi, ICustomFormatProvider nameProvider, string[] nativeDigits = null) { if (dtfi == null) { dtfi = CultureInfo.CurrentUICulture.DateTimeFormat; } if (string.IsNullOrEmpty(format)) { format = nameProvider != null ? nameProvider.ShortDatePattern : dtfi.ShortDatePattern; } else if (format.Length == 1) { switch (format[0]) { case 'D': { format = nameProvider != null ? nameProvider.LongDatePattern : dtfi.LongDatePattern; break; } case 'm': case 'M': { format = nameProvider != null ? nameProvider.MonthDayPattern : dtfi.MonthDayPattern; break; } case 'y': case 'Y': { format = nameProvider != null ? nameProvider.YearMonthPattern : dtfi.YearMonthPattern; break; } default: { format = nameProvider != null ? nameProvider.ShortDatePattern : dtfi.ShortDatePattern; break; } } } format = format.Replace(nameProvider != null ? nameProvider.DateSeparator : dtfi.DateSeparator, "/"); StringBuilder sb = new StringBuilder(); Calendar c = nameProvider != null ? nameProvider.Calendar : dtfi.Calendar; int i = 0; while (i < format.Length) { int tokLen; char ch = format[i]; switch (ch) { case 'd': { tokLen = CountChar(format, i, ch); sb.Append(tokLen <= 2 ? DateMethods.GetNumberString(this.Day, nativeDigits, tokLen == 2) : GetDayName(c.GetDayOfWeek(this.Date), dtfi, nameProvider, tokLen == 3)); break; } case 'M': { tokLen = CountChar(format, i, ch); sb.Append(tokLen <= 2 ? DateMethods.GetNumberString(this.Month, nativeDigits, tokLen == 2) : GetMonthName(this.Month, this.Year, dtfi, nameProvider, tokLen == 3)); break; } case 'y': { tokLen = CountChar(format, i, ch); sb.Append(tokLen <= 2 ? DateMethods.GetNumberString(this.Year % 100, nativeDigits, true) : DateMethods.GetNumberString(this.Year, nativeDigits, false)); break; } case 'g': { tokLen = CountChar(format, i, ch); sb.Append(nameProvider != null ? nameProvider.GetEraName(c.GetEra(this.Date)) : dtfi.GetEraName(c.GetEra(this.Date))); break; } case '/': { tokLen = CountChar(format, i, ch); sb.Append(nameProvider != null ? nameProvider.DateSeparator : dtfi.DateSeparator); break; } case '\'': { tokLen = 1; break; } default: { tokLen = 1; sb.Append(ch.ToString(CultureInfo.CurrentUICulture)); break; } } i += tokLen; } return(sb.ToString()); }
// Token: 0x060015E6 RID: 5606 RVA: 0x00040744 File Offset: 0x0003E944 private static string FormatCustomized(DateTime dateTime, string format, DateTimeFormatInfo dtfi, TimeSpan offset) { Calendar calendar = dtfi.Calendar; StringBuilder stringBuilder = StringBuilderCache.Acquire(16); bool flag = calendar.ID == 8; bool flag2 = calendar.ID == 3; bool timeOnly = true; int i = 0; while (i < format.Length) { char c = format[i]; int num2; if (c <= 'K') { if (c <= '/') { if (c <= '%') { if (c != '"') { if (c != '%') { goto IL_64F; } int num = DateTimeFormat.ParseNextChar(format, i); if (num >= 0 && num != 37) { stringBuilder.Append(DateTimeFormat.FormatCustomized(dateTime, ((char)num).ToString(), dtfi, offset)); num2 = 2; goto IL_65B; } throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } } else if (c != '\'') { if (c != '/') { goto IL_64F; } stringBuilder.Append(dtfi.DateSeparator); num2 = 1; goto IL_65B; } StringBuilder stringBuilder2 = new StringBuilder(); num2 = DateTimeFormat.ParseQuoteString(format, i, stringBuilder2); stringBuilder.Append(stringBuilder2); } else if (c <= 'F') { if (c != ':') { if (c != 'F') { goto IL_64F; } goto IL_1E3; } else { stringBuilder.Append(dtfi.TimeSeparator); num2 = 1; } } else if (c != 'H') { if (c != 'K') { goto IL_64F; } num2 = 1; DateTimeFormat.FormatCustomizedRoundripTimeZone(dateTime, offset, stringBuilder); } else { num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); DateTimeFormat.FormatDigits(stringBuilder, dateTime.Hour, num2); } } else if (c <= 'm') { if (c <= '\\') { if (c != 'M') { if (c != '\\') { goto IL_64F; } int num = DateTimeFormat.ParseNextChar(format, i); if (num < 0) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } stringBuilder.Append((char)num); num2 = 2; } else { num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); int month = calendar.GetMonth(dateTime); if (num2 <= 2) { if (flag) { DateTimeFormat.HebrewFormatDigits(stringBuilder, month); } else { DateTimeFormat.FormatDigits(stringBuilder, month, num2); } } else if (flag) { stringBuilder.Append(DateTimeFormat.FormatHebrewMonthName(dateTime, month, num2, dtfi)); } else if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != DateTimeFormatFlags.None && num2 >= 4) { stringBuilder.Append(dtfi.internalGetMonthName(month, DateTimeFormat.IsUseGenitiveForm(format, i, num2, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false)); } else { stringBuilder.Append(DateTimeFormat.FormatMonth(month, num2, dtfi)); } timeOnly = false; } } else { switch (c) { case 'd': num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num2 <= 2) { int dayOfMonth = calendar.GetDayOfMonth(dateTime); if (flag) { DateTimeFormat.HebrewFormatDigits(stringBuilder, dayOfMonth); } else { DateTimeFormat.FormatDigits(stringBuilder, dayOfMonth, num2); } } else { int dayOfWeek = (int)calendar.GetDayOfWeek(dateTime); stringBuilder.Append(DateTimeFormat.FormatDayOfWeek(dayOfWeek, num2, dtfi)); } timeOnly = false; break; case 'e': goto IL_64F; case 'f': goto IL_1E3; case 'g': num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); stringBuilder.Append(dtfi.GetEraName(calendar.GetEra(dateTime))); break; case 'h': { num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); int num3 = dateTime.Hour % 12; if (num3 == 0) { num3 = 12; } DateTimeFormat.FormatDigits(stringBuilder, num3, num2); break; } default: if (c != 'm') { goto IL_64F; } num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); DateTimeFormat.FormatDigits(stringBuilder, dateTime.Minute, num2); break; } } } else if (c <= 't') { if (c != 's') { if (c != 't') { goto IL_64F; } num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num2 == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { stringBuilder.Append(dtfi.AMDesignator[0]); } } else if (dtfi.PMDesignator.Length >= 1) { stringBuilder.Append(dtfi.PMDesignator[0]); } } else { stringBuilder.Append((dateTime.Hour < 12) ? dtfi.AMDesignator : dtfi.PMDesignator); } } else { num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); DateTimeFormat.FormatDigits(stringBuilder, dateTime.Second, num2); } } else if (c != 'y') { if (c != 'z') { goto IL_64F; } num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); DateTimeFormat.FormatCustomizedTimeZone(dateTime, offset, format, num2, timeOnly, stringBuilder); } else { int year = calendar.GetYear(dateTime); num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (flag2 && !AppContextSwitches.FormatJapaneseFirstYearAsANumber && year == 1 && ((i + num2 < format.Length && format[i + num2] == "年"[0]) || (i + num2 < format.Length - 1 && format[i + num2] == '\'' && format[i + num2 + 1] == "年"[0]))) { stringBuilder.Append("元"[0]); } else if (dtfi.HasForceTwoDigitYears) { DateTimeFormat.FormatDigits(stringBuilder, year, (num2 <= 2) ? num2 : 2); } else if (calendar.ID == 8) { DateTimeFormat.HebrewFormatDigits(stringBuilder, year); } else if (num2 <= 2) { DateTimeFormat.FormatDigits(stringBuilder, year % 100, num2); } else { string format2 = "D" + num2; stringBuilder.Append(year.ToString(format2, CultureInfo.InvariantCulture)); } timeOnly = false; } IL_65B: i += num2; continue; IL_1E3: num2 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num2 > 7) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } long num4 = dateTime.Ticks % 10000000L; num4 /= (long)Math.Pow(10.0, (double)(7 - num2)); if (c == 'f') { stringBuilder.Append(((int)num4).ToString(DateTimeFormat.fixedNumberFormats[num2 - 1], CultureInfo.InvariantCulture)); goto IL_65B; } int num5 = num2; while (num5 > 0 && num4 % 10L == 0L) { num4 /= 10L; num5--; } if (num5 > 0) { stringBuilder.Append(((int)num4).ToString(DateTimeFormat.fixedNumberFormats[num5 - 1], CultureInfo.InvariantCulture)); goto IL_65B; } if (stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] == '.') { stringBuilder.Remove(stringBuilder.Length - 1, 1); goto IL_65B; } goto IL_65B; IL_64F: stringBuilder.Append(c); num2 = 1; goto IL_65B; } return(StringBuilderCache.GetStringAndRelease(stringBuilder)); }
private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi) { Calendar cal = dtfi.Calendar; StringBuilder result = new StringBuilder(); // This is a flag to indicate if we are format the dates using Hebrew calendar. bool isHebrewCalendar = (cal.ID == Calendar.CAL_HEBREW); // This is a flag to indicate if we are formating hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'g': tokenLen = ParseRepeatPattern(format, i, ch); result.Append(dtfi.GetEraName(cal.GetEra(dateTime))); break; case 'h': tokenLen = ParseRepeatPattern(format, i, ch); hour12 = dateTime.Hour % 12; if (hour12 == 0) { hour12 = 12; } FormatDigits(result, hour12, tokenLen); break; case 'H': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Hour, tokenLen); break; case 'm': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Minute, tokenLen); break; case 's': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Second, tokenLen); break; case 'f': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction = fraction / (long)Math.Pow(10, 7 - tokenLen); result.Append(((int)fraction).ToString((new String('0', tokenLen)))); } else { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } break; case 't': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else { if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } } else { result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator)); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-leter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= 2) { int day = cal.GetDayOfMonth(dateTime); if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, day); } else { FormatDigits(result, day, tokenLen); } } else { int dayOfWeek = (int)cal.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi)); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); int month = cal.GetMonth(dateTime); if (tokenLen <= 2) { if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, month); } else { FormatDigits(result, month, tokenLen); } } else { if (isHebrewCalendar) { result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi)); } else { result.Append(FormatMonth(month, tokenLen, dtfi)); } } bTimeOnly = false; break; case 'y': int year = cal.GetYear(dateTime); tokenLen = ParseRepeatPattern(format, i, ch); switch (cal.ID) { // Add a special case for Japanese. // For Japanese calendar, always use two digit (with leading 0) case (Calendar.CAL_JAPAN): FormatDigits(result, year, 2); break; case (Calendar.CAL_HEBREW): HebrewFormatDigits(result, year); break; default: if (tokenLen <= 2) { FormatDigits(result, year % 100, tokenLen); } else { String fmtPattern = "D" + tokenLen; result.Append(year.ToString(fmtPattern)); } break; } bTimeOnly = false; break; case 'z': // // Output the offset of the timezone according to the system timezone setting. // tokenLen = ParseRepeatPattern(format, i, ch); TimeSpan offset; if (bTimeOnly && dateTime.Ticks < Calendar.TicksPerDay) { offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); } else { offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime); } switch (tokenLen) { case 1: result.Append((offset.Hours).ToString("+0;-0")); break; case 2: result.Append((offset.Hours).ToString("+00;-00")); break; default: if (offset.Hours > 0) { result.Append(String.Format("+{0:00}:{1:00}", offset.Hours, offset.Minutes)); } else { // When the offset is negative, note that the offset.Minute is also negative. // So use should use -offset.Minute to get the postive value. result.Append(String.Format("-{0:00}:{1:00}", -offset.Hours, -offset.Minutes)); } break; } break; case ':': result.Append(dtfi.TimeSeparator); tokenLen = 1; break; case '/': result.Append(dtfi.DateSeparator); tokenLen = 1; break; case '\'': case '\"': StringBuilder enquotedString = new StringBuilder(); tokenLen = ParseQuoteString(format, i, enquotedString); result.Append(enquotedString); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For exmple, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar(format, i); if (nextChar >= 0) { result.Append(((char)nextChar)); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append(ch); tokenLen = 1; break; } i += tokenLen; } return(result.ToString()); }
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.HandlePostBackEvent"]/*' /> public override bool HandlePostBackEvent(String eventArgument) { // This is mainly to capture the option picked by the user on // secondary pages and manipulate SecondaryUIMode accordingly so // Render() can generate the appropriate UI. // It also capture the state "Done" which can be set when a date, // a week or a month is selected or entered in some secondary // page. SecondaryUIMode = Int32.Parse(eventArgument, CultureInfo.InvariantCulture); Debug.Assert(NotSecondaryUI == NotSecondaryUIInit); switch (SecondaryUIMode) { case DefaultDateDone: SelectRange(Control.VisibleDate, Control.VisibleDate); goto case Done; case TypeDate: _requireFormTag = true; break; case TypeDateDone: try { String dateText = _textBox.Text; String dateFormat = GetNumericDateFormat(); DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo; int eraIndex = _selectList.SelectedIndex; if (eraIndex >= 0 && eraIndex < currentInfo.Calendar.Eras.Length) { dateText += currentInfo.GetEraName(currentInfo.Calendar.Eras[eraIndex]); dateFormat += "gg"; } DateTime dateTime = DateTime.ParseExact(dateText, dateFormat, null); SelectRange(dateTime, dateTime); Control.VisibleDate = dateTime; } catch { _textBoxErrorMessage = SR.GetString(SR.CalendarAdapterTextBoxErrorMessage); SecondaryUIMode = TypeDate; goto case TypeDate; } goto case Done; case Done: // Set the secondary exit code and raise the selection event for // web page developer to manipulate the selected date. ExitSecondaryUIMode(); _chooseOption = FirstPrompt; break; case DateOption: case WeekOption: case MonthOption: _chooseOption = SecondaryUIMode; // save in the ViewState // In all 3 cases, continue to the UI that chooses a month SecondaryUIMode = ChooseMonth; break; } return(true); }
private void VerificationHelper(DateTimeFormatInfo info, int era, string expected) { string actual = info.GetEraName(era); Assert.Equal(expected, actual); }
private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal <string>(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal <string>(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal <string>(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal <string>(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal <string>(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal <string>(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal <string>(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.True(GetLocaleInfo(ci, LOCALE_S1159).Equals(dtfi.AMDesignator, StringComparison.OrdinalIgnoreCase), String.Format("Failed with AMDesignator for culture {0}", ci)); Assert.True(GetLocaleInfo(ci, LOCALE_S2359).Equals(dtfi.PMDesignator, StringComparison.OrdinalIgnoreCase), String.Format("Failed with PMDesignator for culture {0}", ci)); Assert.True(GetDefaultcalendar(ci) == calId, String.Format("Default calendar not matching for culture {0}. we got {1} and expected {2}", ci, GetDefaultcalendar(ci), calId)); int dayOfWeek = ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK)); Assert.True(dayOfWeek == (int)dtfi.FirstDayOfWeek, String.Format("FirstDayOfWeek is not matching for culture {0}. we got {1} and expected {2}", ci, dayOfWeek, dtfi.FirstDayOfWeek)); Assert.True(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR) == (int)dtfi.CalendarWeekRule, String.Format("CalendarWeekRule is not matching for culture {0}. we got {1} and expected {2}", ci, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR), dtfi.CalendarWeekRule)); string monthDay = GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true); Assert.True(monthDay == dtfi.MonthDayPattern, String.Format("MonthDayPattern is not matching for culture {0}. we got '{1}' and expected '{2}'", ci, monthDay, dtfi.MonthDayPattern)); string rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; Assert.True(rfc1123Pattern == dtfi.RFC1123Pattern, String.Format("RFC1123Pattern is not matching for culture {0}. we got '{1}' and expected '{2}'", ci, dtfi.RFC1123Pattern, rfc1123Pattern)); string sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; Assert.True(sortableDateTimePattern == dtfi.SortableDateTimePattern, String.Format("SortableDateTimePattern is not matching for culture {0}. we got '{1}' and expected '{2}'", ci, dtfi.SortableDateTimePattern, sortableDateTimePattern)); string universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; Assert.True(universalSortableDateTimePattern == dtfi.UniversalSortableDateTimePattern, String.Format("SortableDateTimePattern is not matching for culture {0}. we got '{1}' and expected '{2}'", ci, dtfi.UniversalSortableDateTimePattern, universalSortableDateTimePattern)); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.True(fullDateTimePattern == dtfi.FullDateTimePattern || fullDateTimePattern1 == dtfi.FullDateTimePattern, String.Format("FullDateTimePattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, fullDateTimePattern, fullDateTimePattern1, dtfi.FullDateTimePattern)); Assert.True(longDatePattern1 == dtfi.LongDatePattern || longDatePattern2 == dtfi.LongDatePattern, String.Format("LongDatePattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, longDatePattern1, longDatePattern2, dtfi.LongDatePattern)); Assert.True(longTimePattern1 == dtfi.LongTimePattern || longTimePattern2 == dtfi.LongTimePattern, String.Format("LongTimePattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, longTimePattern1, longTimePattern1, dtfi.LongTimePattern)); string shortTimePattern1 = GetTimeFormats(ci, TIME_NOSECONDS)[0]; string shortTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)); Assert.True(shortTimePattern1 == dtfi.ShortTimePattern || shortTimePattern2 == dtfi.ShortTimePattern, String.Format("ShortTimePattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, shortTimePattern1, shortTimePattern1, dtfi.ShortTimePattern)); string shortDatePattern1 = GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0]; string shortDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)); Assert.True(shortDatePattern1 == dtfi.ShortDatePattern || shortDatePattern2 == dtfi.ShortDatePattern, String.Format("LongDatePattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, shortDatePattern1, shortDatePattern2, dtfi.ShortDatePattern)); string yearMonthPattern1 = GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0]; string yearMonthPattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)); Assert.True(yearMonthPattern1 == dtfi.YearMonthPattern || yearMonthPattern2 == dtfi.YearMonthPattern, String.Format("YearMonthPattern is not matching for culture {0}. we got '{1}' or '{2}' and expected '{3}'", ci, yearMonthPattern1, yearMonthPattern2, dtfi.YearMonthPattern)); string[] eraNames = GetCalendarInfo(ci, calId, CAL_SERASTRING); Assert.True(eraNames[0].Equals(dtfi.GetEraName(1), StringComparison.OrdinalIgnoreCase), String.Format("Era 1 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetEraName(1), eraNames[0])); if (cal is JapaneseCalendar) { Assert.True(eraNames[1].Equals(dtfi.GetEraName(2), StringComparison.OrdinalIgnoreCase), String.Format("Era 2 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetEraName(2), eraNames[1])); Assert.True(eraNames[2].Equals(dtfi.GetEraName(3), StringComparison.OrdinalIgnoreCase), String.Format("Era 3 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetEraName(3), eraNames[2])); Assert.True(eraNames[3].Equals(dtfi.GetEraName(4), StringComparison.OrdinalIgnoreCase), String.Format("Era 4 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetEraName(4), eraNames[3])); } string[] abbreviatedEraNames = GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING); Assert.True(abbreviatedEraNames[0].Equals(dtfi.GetAbbreviatedEraName(1), StringComparison.OrdinalIgnoreCase), String.Format("Abbreviated Era 1 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetAbbreviatedEraName(1), abbreviatedEraNames[0])); if (cal is JapaneseCalendar) { Assert.True(abbreviatedEraNames[1].Equals(dtfi.GetAbbreviatedEraName(2), StringComparison.OrdinalIgnoreCase), String.Format("Abbreviated Era 1 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetAbbreviatedEraName(2), abbreviatedEraNames[1])); Assert.True(abbreviatedEraNames[2].Equals(dtfi.GetAbbreviatedEraName(3), StringComparison.OrdinalIgnoreCase), String.Format("Abbreviated Era 1 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetAbbreviatedEraName(3), abbreviatedEraNames[2])); Assert.True(abbreviatedEraNames[3].Equals(dtfi.GetAbbreviatedEraName(4), StringComparison.OrdinalIgnoreCase), String.Format("Abbreviated Era 1 Name with culture {0} and calendar {1} is wrong. got {2} and expected {3}", ci, cal, dtfi.GetAbbreviatedEraName(4), abbreviatedEraNames[3])); } }
/// <summary> /// Returns a string representation of this object. /// </summary> /// <param name="format">The format pattern.</param> /// <param name="dtfi">The <see cref="DateTimeFormatInfo"/> to use for formatting.</param> /// <param name="nameProvider">The day and month name provider.</param> /// <returns></returns> private string ToString(string format, DateTimeFormatInfo dtfi, ICustomFormatProvider nameProvider) { if (dtfi == null) { dtfi = CultureInfo.CurrentUICulture.DateTimeFormat; } bool rtlCulture = nameProvider != null ? nameProvider.IsRTLLanguage : false; if (string.IsNullOrEmpty(format)) { format = nameProvider != null ? nameProvider.ShortDatePattern : dtfi.ShortDatePattern; } else if (format.Length == 1) { switch (format[0]) { case 'D': { format = nameProvider != null ? nameProvider.LongDatePattern : dtfi.LongDatePattern; break; } case 'm': case 'M': { format = nameProvider != null ? nameProvider.MonthDayPattern : dtfi.MonthDayPattern; break; } case 'y': case 'Y': { format = nameProvider != null ? nameProvider.YearMonthPattern : dtfi.YearMonthPattern; break; } default: { format = nameProvider != null ? nameProvider.YearMonthPattern : dtfi.ShortDatePattern; break; } } } format = format.Replace(nameProvider != null ? nameProvider.DateSeparator : dtfi.DateSeparator, "/"); StringBuilder sb = new StringBuilder(); const string rtlCode = "\u200F"; const string ltrCode = "\u200E"; Calendar c = nameProvider != null ? nameProvider.Calendar : dtfi.Calendar; int i = 0; while (i < format.Length) { int tokLen; char ch = format[i]; switch (ch) { case 'd': { tokLen = CountChar(format, i, ch); if (tokLen <= 2) { sb.Append(rtlCulture ? rtlCode : ltrCode).Append(tokLen == 2 ? this.Day.ToString("##00") : this.Day.ToString()); } else { sb.Append(rtlCulture ? rtlCode : ltrCode).Append(GetDayName(c.GetDayOfWeek(this.Date), dtfi, nameProvider, tokLen == 3)); } break; } case 'M': { tokLen = CountChar(format, i, ch); if (tokLen <= 2) { sb.Append(rtlCulture ? rtlCode : ltrCode).Append(tokLen == 2 ? this.Month.ToString("##00") : this.Month.ToString()); } else { sb.Append(rtlCulture ? rtlCode : ltrCode).Append(GetMonthName(this.Month, this.Year, dtfi, nameProvider, tokLen == 3)); } break; } case 'y': { tokLen = CountChar(format, i, ch); if (tokLen <= 2) { sb.Append(rtlCulture ? rtlCode : ltrCode).Append((this.Year % 100).ToString("##00")); } else { sb.Append(rtlCulture ? rtlCode : ltrCode).Append(this.Year.ToString()); } break; } case 'g': { tokLen = CountChar(format, i, ch); sb.Append(rtlCulture ? rtlCode : ltrCode).Append(nameProvider != null ? nameProvider.GetEraName(c.GetEra(this.Date)) : dtfi.GetEraName(c.GetEra(this.Date))); break; } case '/': { tokLen = CountChar(format, i, ch); sb.Append(rtlCulture ? rtlCode : ltrCode).Append(nameProvider != null ? nameProvider.DateSeparator : dtfi.DateSeparator); break; } case '\'': { tokLen = 1; break; } default: { tokLen = 1; sb.Append(rtlCulture ? rtlCode : ltrCode).Append(ch.ToString()); break; } } i += tokLen; } return(sb.ToString()); }
protected override void OnPaint(PaintEventArgs e) { BitmapPainter painter = new BitmapPainter(e); Graphics g = painter.Graphics; if (g == null) { return; } // // Brushes // Brush textHightLight = CalendarStatics.DarkDarkBrush; Brush textBrush = CalendarStatics.WindowTextBrush; Brush hightLightBrush = CalendarStatics.ControlBrush; // // String Format // _stringFormat.Alignment = StringAlignment.Center; _stringFormat.LineAlignment = StringAlignment.Center; // // DateTimeFormatInfo // String[] MonthNames = _formatInfo.MonthNames; Rectangle rect = ClientRectangle; g.FillRectangle(CalendarStatics.WindowBrush, rect); rect.Width--; // Paint Calendar Name rect.X = 6; rect.Width -= 12; rect.Y = 4; rect.Height = 17; g.FillRectangle(hightLightBrush, rect); g.DrawString(_calendarName, Font, textBrush, rect, _stringFormat); // // Paint start, End dates // string formattedStartDate, formattedEndDate; formattedStartDate = _hostedCalendar.GetMonth(_startDate).ToString(CultureInfo.InvariantCulture) + "/" + _hostedCalendar.GetDayOfMonth(_startDate).ToString(CultureInfo.InvariantCulture) + "/" + _hostedCalendar.GetYear(_startDate).ToString(CultureInfo.InvariantCulture); formattedEndDate = _hostedCalendar.GetMonth(_endDate).ToString(CultureInfo.InvariantCulture) + "/" + _hostedCalendar.GetDayOfMonth(_endDate).ToString(CultureInfo.InvariantCulture) + "/" + _hostedCalendar.GetYear(_endDate).ToString(CultureInfo.InvariantCulture); rect.Y += 17; g.DrawString(formattedStartDate, Font, textBrush, rect, _stringFormat); rect.Y += 17; g.DrawString(formattedEndDate, Font, textBrush, rect, _stringFormat); // // Paint Day of Week title // rect.Y += 17; g.FillRectangle(hightLightBrush, rect); rect.X = 0; rect.Width = CalendarStatics.CellWidth; rect.Height = CalendarStatics.CellHeight; _stringFormat.Alignment = StringAlignment.Far; for (int i = 0; i < _dayNames.GetLength(0); i++) { rect.X = CalendarStatics.Indent + (CalendarStatics.CellWidth * i); g.DrawString(_dayNames[i], Font, textBrush, rect, _stringFormat); } rect.Y += 19; g.DrawLine(CalendarStatics.DarkPen, CalendarStatics.Indent, rect.Y, 132, rect.Y); // Paint the days DateTime date = new DateTime(_startDate.Year, _startDate.Month, _startDate.Day); int j = (int)CalendarStatics.gregorian.GetDayOfWeek(date); rect.Width = CalendarStatics.CellWidth; rect.Height = CalendarStatics.CellHeight; _daysYPosition = rect.Y; int whichDay = 1; do { rect.X = CalendarStatics.Indent + (CalendarStatics.CellWidth * j); if (whichDay == _markedDay) { g.DrawRectangle(CalendarStatics.DarkDarkPen, rect); g.FillRectangle(CalendarStatics.DarkBrush, rect); } whichDay++; g.DrawString(_hostedCalendar.GetDayOfMonth(date).ToString(CultureInfo.InvariantCulture), Font, textBrush, rect, _stringFormat); j++; if (j == 7) { j = 0; rect.Y += CalendarStatics.CellHeight + 2; } date = date.AddDays(1); } while (date < _endDate); if (date <= _hostedCalendar.MaxSupportedDateTime) { rect.X = CalendarStatics.Indent + (CalendarStatics.CellWidth * j); if (whichDay == _markedDay) { g.DrawRectangle(CalendarStatics.DarkDarkPen, rect); g.FillRectangle(CalendarStatics.DarkBrush, rect); } g.DrawString(_hostedCalendar.GetDayOfMonth(date).ToString(CultureInfo.InvariantCulture), Font, textBrush, rect, _stringFormat); } rect.Y += 19; g.DrawLine(CalendarStatics.DarkPen, CalendarStatics.Indent, rect.Y, 132, rect.Y); // // Draw the Era and month names // _stringFormat.Alignment = StringAlignment.Near; rect.X = CalendarStatics.Indent; rect.Y += 2; rect.Width = CalendarStatics.ClientWidth - rect.X; int era = _hostedCalendar.GetEra(_startDate); g.DrawString("Era: " + era.ToString(CultureInfo.InvariantCulture) + " " + _formatInfo.GetEraName(era), Font, textBrush, rect, _stringFormat); rect.Y += 17; if (_canBeOptionalCalendar) { formattedStartDate = _startDate.ToString("MMMM", _formatInfo) + " ~ " + _endDate.ToString("MMMM", _formatInfo); g.DrawString(formattedStartDate, Font, textBrush, rect, _stringFormat); } painter.Flush(); // Year TextBox SetYearText(); }
private static JObject CreateDateInfoJson(DateTimeFormatInfo di) { var obj = new { firstDay = di.FirstDayOfWeek, days = new { names = di.DayNames, namesAbbr = di.AbbreviatedDayNames, namesShort = di.ShortestDayNames }, months = new { names = di.MonthNames, namesAbbr = di.AbbreviatedMonthNames }, AM = new[] { di.AMDesignator, di.AMDesignator.ToLower(), di.AMDesignator.ToUpper() }, PM = new[] { di.PMDesignator, di.PMDesignator.ToLower(), di.PMDesignator.ToUpper() }, eras = di.Calendar.Eras.Select(era => new { offset = 0, start = (string)null, name = di.GetEraName(era) }).ToArray(), twoDigitYearMax = di.Calendar.TwoDigitYearMax, patterns = new { d = di.ShortDatePattern, D = di.LongDatePattern, t = di.ShortTimePattern, T = di.LongTimePattern, f = di.LongDatePattern + " " + di.ShortTimePattern, F = di.LongDatePattern + " " + di.LongTimePattern, M = di.MonthDayPattern, Y = di.YearMonthPattern, } }; var jobj = JObject.FromObject(obj); jobj["/"] = di.DateSeparator; jobj[":"] = di.TimeSeparator; if (!di.MonthNames.SequenceEqual(di.MonthGenitiveNames)) { var monthsGenitive = jobj["monthsGenitive"] = new JObject(); monthsGenitive["names"] = JArray.FromObject(di.MonthGenitiveNames); monthsGenitive["namesAbbr"] = JArray.FromObject(di.AbbreviatedMonthGenitiveNames); } return(new JObject() { { "standard", jobj } }); }
private static string FormatCustomized(DateTime dateTime, string format, DateTimeFormatInfo dtfi, TimeSpan offset) { Calendar calendar = dtfi.Calendar; StringBuilder stringBuilder1 = StringBuilderCache.Acquire(16); bool flag = calendar.ID == 8; bool timeOnly = true; int index1 = 0; while (index1 < format.Length) { char patternChar = format[index1]; int num1; if ((uint)patternChar <= 75U) { if ((uint)patternChar <= 47U) { if ((uint)patternChar <= 37U) { if ((int)patternChar != 34) { if ((int)patternChar == 37) { int nextChar = DateTimeFormat.ParseNextChar(format, index1); if (nextChar < 0 || nextChar == 37) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } stringBuilder1.Append(DateTimeFormat.FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset)); num1 = 2; goto label_85; } else { goto label_84; } } } else if ((int)patternChar != 39) { if ((int)patternChar == 47) { stringBuilder1.Append(dtfi.DateSeparator); num1 = 1; goto label_85; } else { goto label_84; } } StringBuilder result = new StringBuilder(); num1 = DateTimeFormat.ParseQuoteString(format, index1, result); stringBuilder1.Append((object)result); goto label_85; } else if ((uint)patternChar <= 70U) { if ((int)patternChar != 58) { if ((int)patternChar != 70) { goto label_84; } } else { stringBuilder1.Append(dtfi.TimeSeparator); num1 = 1; goto label_85; } } else if ((int)patternChar != 72) { if ((int)patternChar == 75) { num1 = 1; DateTimeFormat.FormatCustomizedRoundripTimeZone(dateTime, offset, stringBuilder1); goto label_85; } else { goto label_84; } } else { num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); DateTimeFormat.FormatDigits(stringBuilder1, dateTime.Hour, num1); goto label_85; } } else if ((uint)patternChar <= 109U) { if ((uint)patternChar <= 92U) { if ((int)patternChar != 77) { if ((int)patternChar == 92) { int nextChar = DateTimeFormat.ParseNextChar(format, index1); if (nextChar < 0) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } stringBuilder1.Append((char)nextChar); num1 = 2; goto label_85; } else { goto label_84; } } else { num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); int month = calendar.GetMonth(dateTime); if (num1 <= 2) { if (flag) { DateTimeFormat.HebrewFormatDigits(stringBuilder1, month); } else { DateTimeFormat.FormatDigits(stringBuilder1, month, num1); } } else if (flag) { stringBuilder1.Append(DateTimeFormat.FormatHebrewMonthName(dateTime, month, num1, dtfi)); } else if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != DateTimeFormatFlags.None && num1 >= 4) { stringBuilder1.Append(dtfi.internalGetMonthName(month, DateTimeFormat.IsUseGenitiveForm(format, index1, num1, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false)); } else { stringBuilder1.Append(DateTimeFormat.FormatMonth(month, num1, dtfi)); } timeOnly = false; goto label_85; } } else { switch (patternChar) { case 'd': num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); if (num1 <= 2) { int dayOfMonth = calendar.GetDayOfMonth(dateTime); if (flag) { DateTimeFormat.HebrewFormatDigits(stringBuilder1, dayOfMonth); } else { DateTimeFormat.FormatDigits(stringBuilder1, dayOfMonth, num1); } } else { int dayOfWeek = (int)calendar.GetDayOfWeek(dateTime); stringBuilder1.Append(DateTimeFormat.FormatDayOfWeek(dayOfWeek, num1, dtfi)); } timeOnly = false; goto label_85; case 'f': break; case 'g': num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); stringBuilder1.Append(dtfi.GetEraName(calendar.GetEra(dateTime))); goto label_85; case 'h': num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); int num2 = dateTime.Hour % 12; if (num2 == 0) { num2 = 12; } DateTimeFormat.FormatDigits(stringBuilder1, num2, num1); goto label_85; case 'm': num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); DateTimeFormat.FormatDigits(stringBuilder1, dateTime.Minute, num1); goto label_85; default: goto label_84; } } } else if ((uint)patternChar <= 116U) { if ((int)patternChar != 115) { if ((int)patternChar == 116) { num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); if (num1 == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { stringBuilder1.Append(dtfi.AMDesignator[0]); goto label_85; } else { goto label_85; } } else if (dtfi.PMDesignator.Length >= 1) { stringBuilder1.Append(dtfi.PMDesignator[0]); goto label_85; } else { goto label_85; } } else { stringBuilder1.Append(dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator); goto label_85; } } else { goto label_84; } } else { num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); DateTimeFormat.FormatDigits(stringBuilder1, dateTime.Second, num1); goto label_85; } } else if ((int)patternChar != 121) { if ((int)patternChar == 122) { num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); DateTimeFormat.FormatCustomizedTimeZone(dateTime, offset, format, num1, timeOnly, stringBuilder1); goto label_85; } else { goto label_84; } } else { int year = calendar.GetYear(dateTime); num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); if (dtfi.HasForceTwoDigitYears) { DateTimeFormat.FormatDigits(stringBuilder1, year, num1 <= 2 ? num1 : 2); } else if (calendar.ID == 8) { DateTimeFormat.HebrewFormatDigits(stringBuilder1, year); } else if (num1 <= 2) { DateTimeFormat.FormatDigits(stringBuilder1, year % 100, num1); } else { string format1 = "D" + (object)num1; stringBuilder1.Append(year.ToString(format1, (IFormatProvider)CultureInfo.InvariantCulture)); } timeOnly = false; goto label_85; } num1 = DateTimeFormat.ParseRepeatPattern(format, index1, patternChar); if (num1 > 7) { throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } long num3 = dateTime.Ticks % 10000000L / (long)Math.Pow(10.0, (double)(7 - num1)); if ((int)patternChar == 102) { stringBuilder1.Append(((int)num3).ToString(DateTimeFormat.fixedNumberFormats[num1 - 1], (IFormatProvider)CultureInfo.InvariantCulture)); goto label_85; } else { int num4; for (num4 = num1; num4 > 0 && num3 % 10L == 0L; --num4) { num3 /= 10L; } if (num4 > 0) { stringBuilder1.Append(((int)num3).ToString(DateTimeFormat.fixedNumberFormats[num4 - 1], (IFormatProvider)CultureInfo.InvariantCulture)); goto label_85; } else if (stringBuilder1.Length > 0) { StringBuilder stringBuilder2 = stringBuilder1; int index2 = stringBuilder2.Length - 1; if ((int)stringBuilder2[index2] == 46) { StringBuilder stringBuilder3 = stringBuilder1; int startIndex = stringBuilder3.Length - 1; int length = 1; stringBuilder3.Remove(startIndex, length); goto label_85; } else { goto label_85; } } else { goto label_85; } } label_84: stringBuilder1.Append(patternChar); num1 = 1; label_85: index1 += num1; } return(StringBuilderCache.GetStringAndRelease(stringBuilder1)); }
private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(calId, GetDefaultcalendar(ci)); Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK))); Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR)); Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true)); Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern); Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern); Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 }); Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 }); Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 }); Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) }); Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) }); Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) }); int eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); }
public void GetEraName_InvalidEra_ThrowsArgumentOutOfRangeException(int era) { var format = new DateTimeFormatInfo(); AssertExtensions.Throws <ArgumentOutOfRangeException>("era", () => format.GetEraName(era)); }
public static string ToString(DateTime dt, TimeSpan?utc_offset, string format, DateTimeFormatInfo dfi) { StringBuilder stringBuilder = new StringBuilder(format.Length + 10); DateTimeFormatInfo invariantInfo = DateTimeFormatInfo.InvariantInfo; if (format == invariantInfo.RFC1123Pattern) { dfi = invariantInfo; } else if (format == invariantInfo.UniversalSortableDateTimePattern) { dfi = invariantInfo; } int i = 0; while (i < format.Length) { bool flag = false; char c = format[i]; char c2 = c; int num; switch (c2) { case 'd': num = DateTimeUtils.CountRepeat(format, i, c); if (num <= 2) { DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetDayOfMonth(dt), (num != 1) ? 2 : 1); } else if (num == 3) { stringBuilder.Append(dfi.GetAbbreviatedDayName(dfi.Calendar.GetDayOfWeek(dt))); } else { stringBuilder.Append(dfi.GetDayName(dfi.Calendar.GetDayOfWeek(dt))); } break; default: switch (c2) { case 'F': flag = true; goto IL_1E3; default: switch (c2) { case 's': num = DateTimeUtils.CountRepeat(format, i, c); DateTimeUtils.ZeroPad(stringBuilder, dt.Second, (num != 1) ? 2 : 1); break; case 't': { num = DateTimeUtils.CountRepeat(format, i, c); string text = (dt.Hour >= 12) ? dfi.PMDesignator : dfi.AMDesignator; if (num == 1) { if (text.Length >= 1) { stringBuilder.Append(text[0]); } } else { stringBuilder.Append(text); } break; } default: switch (c2) { case '"': case '\'': num = DateTimeUtils.ParseQuotedString(format, i, stringBuilder); break; default: if (c2 != '/') { if (c2 != ':') { if (c2 != '\\') { stringBuilder.Append(c); num = 1; } else { if (i >= format.Length - 1) { throw new FormatException("\\ at end of date time string"); } stringBuilder.Append(format[i + 1]); num = 2; } } else { stringBuilder.Append(dfi.TimeSeparator); num = 1; } } else { stringBuilder.Append(dfi.DateSeparator); num = 1; } 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"); } num = 1; break; } break; case 'y': num = DateTimeUtils.CountRepeat(format, i, c); if (num <= 2) { DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetYear(dt) % 100, num); } else { DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetYear(dt), num); } break; case 'z': { num = DateTimeUtils.CountRepeat(format, i, c); TimeSpan timeSpan = (utc_offset == null) ? TimeZone.CurrentTimeZone.GetUtcOffset(dt) : utc_offset.Value; if (timeSpan.Ticks >= 0L) { stringBuilder.Append('+'); } else { stringBuilder.Append('-'); } int num2 = num; if (num2 != 1) { if (num2 != 2) { stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00")); stringBuilder.Append(':'); stringBuilder.Append(Math.Abs(timeSpan.Minutes).ToString("00")); } else { stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00")); } } else { stringBuilder.Append(Math.Abs(timeSpan.Hours)); } break; } } break; case 'H': num = DateTimeUtils.CountRepeat(format, i, c); DateTimeUtils.ZeroPad(stringBuilder, dt.Hour, (num != 1) ? 2 : 1); break; case 'K': num = 1; if (utc_offset != null || dt.Kind == DateTimeKind.Local) { TimeSpan timeSpan = (utc_offset == null) ? TimeZone.CurrentTimeZone.GetUtcOffset(dt) : utc_offset.Value; if (timeSpan.Ticks >= 0L) { stringBuilder.Append('+'); } else { stringBuilder.Append('-'); } stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00")); stringBuilder.Append(':'); stringBuilder.Append(Math.Abs(timeSpan.Minutes).ToString("00")); } else if (dt.Kind == DateTimeKind.Utc) { stringBuilder.Append('Z'); } break; case 'M': { num = DateTimeUtils.CountRepeat(format, i, c); int month = dfi.Calendar.GetMonth(dt); if (num <= 2) { DateTimeUtils.ZeroPad(stringBuilder, month, num); } else if (num == 3) { stringBuilder.Append(dfi.GetAbbreviatedMonthName(month)); } else { stringBuilder.Append(dfi.GetMonthName(month)); } break; } } break; case 'f': goto IL_1E3; case 'g': num = DateTimeUtils.CountRepeat(format, i, c); stringBuilder.Append(dfi.GetEraName(dfi.Calendar.GetEra(dt))); break; case 'h': { num = DateTimeUtils.CountRepeat(format, i, c); int num3 = dt.Hour % 12; if (num3 == 0) { num3 = 12; } DateTimeUtils.ZeroPad(stringBuilder, num3, (num != 1) ? 2 : 1); break; } case 'm': num = DateTimeUtils.CountRepeat(format, i, c); DateTimeUtils.ZeroPad(stringBuilder, dt.Minute, (num != 1) ? 2 : 1); break; } IL_6C6: i += num; continue; IL_1E3: num = DateTimeUtils.CountRepeat(format, i, c); if (num > 7) { throw new FormatException("Invalid Format String"); } int num4 = (int)(dt.Ticks % 10000000L / (long)Math.Pow(10.0, (double)(7 - num))); int length = stringBuilder.Length; DateTimeUtils.ZeroPad(stringBuilder, num4, num); if (flag) { while (stringBuilder.Length > length && stringBuilder[stringBuilder.Length - 1] == '0') { stringBuilder.Length--; } if (num4 == 0 && length > 0 && stringBuilder[length - 1] == '.') { stringBuilder.Length--; } } goto IL_6C6; } return(stringBuilder.ToString()); }
private ClientCultureInfo(CultureInfo cultureInfo) { name = cultureInfo.Name; numberFormat = cultureInfo.NumberFormat; dateTimeFormat = cultureInfo.DateTimeFormat; var calendar = dateTimeFormat == null ? null : dateTimeFormat.Calendar; if (calendar != null) { // Dev10 425049: Support Eras for gregorian based calendars // with a simple year offset, and non-gregorian calendars. // Era data is stored in binary resource "culture.nlp" in mscorlib, // hard coded here for simplicity. // era array has the following structure: // [eraNumber1, eraName1, eraStartInTicks1, eraGregorianYearOffset1, eraNumber2, ...] eras = new object[calendar.Eras.Length * 4]; int i = 0; foreach (int era in calendar.Eras) { // era number eras[i + eraNumber] = era; // era name eras[i + eraName] = dateTimeFormat.GetEraName(era); // calendars with only one era will have a null tick count // signifying that the era starts from the lowest datetime // era begining in ticks (null = the oldest era) // eras[i + eraStart] = null; // era year offset from normal gregorian year // some calendars dont have an offset, just a different name // for the A.D. era (B.C. is not supported by normal calendar, // so most calendars only have 1 era) eras[i + eraYearOffset] = 0; i += 4; } var calendarType = calendar.GetType(); if (calendarType != typeof(GregorianCalendar)) { if (calendarType == typeof(TaiwanCalendar)) { // Only the current era is supported, so no tick count is needed //eras[eraStart] = -1830384000000; eras[eraYearOffset] = 1911; } else if (calendarType == typeof(KoreanCalendar)) { // only one era to speak of, so no tick count is needed //eras[eraStart] = -62135596800000; eras[eraYearOffset] = -2333; } else if (calendarType == typeof(ThaiBuddhistCalendar)) { // only one era to speak of, so no tick count is needed //eras[eraStart] = -62135596800000; eras[eraYearOffset] = -543; } else if (calendarType == typeof(JapaneseCalendar)) { // there are multiple eras eras[0 + eraStart] = 60022080000; eras[0 + eraYearOffset] = 1988; eras[4 + eraStart] = -1357603200000; eras[4 + eraYearOffset] = 1925; eras[8 + eraStart] = -1812153600000; eras[8 + eraYearOffset] = 1911; // oldest era is technically from this offset, but for simplicity // it is counted from the lowest date time, so no tick count needed. //eras[12 + eraStart] = -3218832000000; eras[12 + eraYearOffset] = 1867; } else if (calendarType == typeof(HijriCalendar)) { _convertScript = "Date.HijriCalendar.js"; _adjustment = ((HijriCalendar)calendar).HijriAdjustment; } else if (calendarType == typeof(UmAlQuraCalendar)) { _convertScript = "Date.UmAlQuraCalendar.js"; } // else { other calendars arent supported or have no era offsets just different names for A.D. } } }
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()); }
// Format a date value as a string using a particular pattern format. public static String Format(String format, DateTime date, DateTimeFormatInfo info) { // Format the date/time value. StringBuilder builder = new StringBuilder(); int posn = 0; char ch; int count, value; while (posn < format.Length) { // Extract the next format character plus its count. ch = format[posn++]; count = 1; switch (ch) { case 'd': case 'm': case 'M': case 'y': case 'g': case 'h': case 'H': case 's': case 'f': case 't': case 'z': { while (posn < format.Length && format[posn] == ch) { ++posn; ++count; } } break; case ':': { builder.Append(info.TimeSeparator); continue; } // Not reached. case '/': { builder.Append(info.DateSeparator); continue; } // Not reached. case '%': { // Used to escape custom patterns that would // otherwise look like single-letter formats. continue; } // Not reached. case '\\': { // Escape the next character. if (posn < format.Length) { builder.Append(format[posn++]); } continue; } // Not reached. case '\'': { // Quoted text. while (posn < format.Length) { ch = format[posn++]; if (ch == '\'') { break; } builder.Append(ch); } continue; } // Not reached. default: { // Literal character. builder.Append(ch); continue; } // Not reached. } // Process the format character. switch (ch) { case 'd': { // Output the day or weekday. if (count == 1) { value = date.Day; if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else if (count == 2) { value = date.Day; builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } else if (count == 3) { builder.Append (info.AbbreviatedDayNames [(int)(date.DayOfWeek)]); } else { builder.Append (info.DayNames[(int)(date.DayOfWeek)]); } } break; case 'M': { // Output the month. value = date.Month; if (count == 1) { if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else if (count == 2) { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } else if (count == 3) { builder.Append (info.AbbreviatedMonthNames[value - 1]); } else { builder.Append(info.MonthNames[value - 1]); } } break; case 'y': { // Output the year. value = date.Year; if (count == 1) { value %= 100; if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else if (count == 2) { value %= 100; builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } else { builder.Append((char)('0' + (value / 1000))); builder.Append ((char)('0' + ((value / 100 % 10)))); builder.Append ((char)('0' + ((value / 10 % 10)))); builder.Append((char)('0' + (value % 10))); } } break; case 'g': { // Output the era name. try { int era = info.Calendar.GetEra(date); builder.Append(info.GetEraName(era)); } catch (ArgumentException) { // The date does not have an era. } } break; case 'h': { // Output the hour in 12-hour format. value = date.Hour; if (value == 0) { value = 12; } else if (value > 12) { value -= 12; } if (count == 1) { if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } break; case 'H': { // Output the hour in 24-hour format. value = date.Hour; if (count == 1) { if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } break; case 'm': { // Output the minute. value = date.Minute; if (count == 1) { if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } break; case 's': { // Output the second. value = date.Second; if (count == 1) { if (value < 10) { builder.Append((char)('0' + value)); } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } else { builder.Append((char)('0' + (value / 10))); builder.Append((char)('0' + (value % 10))); } } break; case 'f': { // Output fractions of a second. if (count > 7) { count = 7; } long frac = date.Ticks; long divisor = TimeSpan.TicksPerSecond; while (count > 0) { divisor /= 10; value = (int)((frac / divisor) % 10); builder.Append((char)('0' + value)); frac %= divisor; --count; } } break; case 't': { value = date.Hour; if (count == 1) { if (value < 12) { builder.Append(info.AMDesignator[0]); } else { builder.Append(info.PMDesignator[0]); } } else { if (value < 12) { builder.Append(info.AMDesignator); } else { builder.Append(info.PMDesignator); } } } break; #if !ECMA_COMPAT case 'z': { long offset = TimeZone.CurrentTimeZone .GetUtcOffset(date).Ticks; int hour, min; if (offset >= 0) { builder.Append('+'); } else { builder.Append('-'); offset = -offset; } hour = (int)(offset / TimeSpan.TicksPerHour); offset %= TimeSpan.TicksPerHour; min = (int)(offset / TimeSpan.TicksPerMinute); if (count == 1) { if (hour < 10) { builder.Append((char)('0' + hour)); } else { builder.Append((char)('0' + (hour / 10))); builder.Append((char)('0' + (hour % 10))); } } else if (count == 2) { builder.Append((char)('0' + (hour / 10))); builder.Append((char)('0' + (hour % 10))); } else { builder.Append((char)('0' + (hour / 10))); builder.Append((char)('0' + (hour % 10))); builder.Append(':'); builder.Append((char)('0' + (min / 10))); builder.Append((char)('0' + (min % 10))); } } break; #endif } } // Return the formatted string to the caller. return(builder.ToString()); }