System.DateTimeFormat.FormatCustomized C# (CSharp) Méthode

FormatCustomized() private static méthode

private static FormatCustomized ( System.DateTime dateTime, String format, DateTimeFormatInfo dtfi ) : String
dateTime System.DateTime
format String
dtfi System.Globalization.DateTimeFormatInfo
Résultat String
        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':
                    case 'F':
                        tokenLen = ParseRepeatPattern(format, i, ch);
                        if (tokenLen <= MaxSecondsFractionDigits) {
                            long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
                            fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
                            if (ch == 'f') {
                                result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
                            }
                            else {
                                int effectiveDigits = tokenLen;
                                while (effectiveDigits > 0) {
                                    if (fraction % 10 == 0) {
                                        fraction = fraction / 10;
                                        effectiveDigits--;
                                    }
                                    else {
                                        break;
                                    }
                                }
                                if (effectiveDigits > 0) {
                                    result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
                                }
                                else {
                                    // No fraction to emit, so see if we should remove decimal also.
                                    if (result.Length > 0 && result[result.Length - 1] == '.') {
                                        result.Remove(result.Length - 1, 1);
                                    }
                                }
                            }
                        } 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 {             
                                if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) {
                                    result.Append(
                                        dtfi.internalGetMonthName(
                                            month, 
                                            IsUseGenitiveForm(format, i, tokenLen, 'd')? MonthNameStyles.Genitive : MonthNameStyles.Regular, 
                                            false));
                                } else {
                                result.Append(FormatMonth(month, tokenLen, dtfi));
                            }
                        }
                        }
                        bTimeOnly = false;
                        break;
                    case 'y':
                        // Notes about OS behavior:
                        // y: Always print (year % 100). No leading zero.
                        // yy: Always print (year % 100) with leading zero.
                        // yyy/yyyy/yyyyy/... : Print year value.  No leading zero.

                        int year = cal.GetYear(dateTime);
                        tokenLen = ParseRepeatPattern(format, i, ch);
                        if (dtfi.HasForceTwoDigitYears) {
                            FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
                        }
                        else if (cal.ID == Calendar.CAL_HEBREW) {
                            HebrewFormatDigits(result, year);
                        }
                        else {
                            if (tokenLen <= 2) {
                                FormatDigits(result, year % 100, tokenLen);
                            }
                            else {
                                String fmtPattern = "D" + tokenLen;
                                result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
                            }
                        }
                        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 {
                            if (dateTime.Kind == DateTimeKind.Utc) {
                                InvalidFormatForUtc(format, dateTime);
                                offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Local));
                            }
                            else {
                                offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
                            }
                        }
    
                        switch (tokenLen)
                        {
                            case 1:
                                result.Append((offset.Hours).ToString("+0;-0", CultureInfo.InvariantCulture));
                                break;
                            case 2:
                                result.Append((offset.Hours).ToString("+00;-00", CultureInfo.InvariantCulture));
                                break;
                            default:
                                if (offset.Ticks >= 0) {
                                    result.Append(String.Format(CultureInfo.InvariantCulture, "+{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(CultureInfo.InvariantCulture, "-{0:00}:{1:00}", -offset.Hours, -offset.Minutes));
                                }
                                break;                        
                        }
                        break;
                    case 'K':
                        tokenLen = 1;
                        // The objective of this format is to round trip the Kind value and preserve the time zone
                        switch (dateTime.Kind) {
                            case DateTimeKind.Local: 
                                // This should output the local offset, e.g. "-07:00"
                                TimeSpan localOffset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
                                if (localOffset.Ticks >= 0) {
                                    result.Append(String.Format(CultureInfo.InvariantCulture, "+{0:00}:{1:00}", localOffset.Hours, localOffset.Minutes));
                                } else {
                                    // When the offset is negative, note that the localOffset.Minute is also negative.
                                    // So use should use -localOffset.Minute to get the postive value.
                                    result.Append(String.Format(CultureInfo.InvariantCulture, "-{0:00}:{1:00}", -localOffset.Hours, -localOffset.Minutes));
                                }
                                break;
                            case DateTimeKind.Utc:
                                // The 'Z' constant is a marker for a UTC date
                                result.Append("Z");
                                break;
                            default:
                                // If the kind is unspecified, we output nothing here
                                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 '\\':
                        //
                        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:
                        result.Append(ch);
                        tokenLen = 1;
                        break;
                }
                i += tokenLen;
            }
            return (result.ToString());
        }
    

Usage Example

        // 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));
        }
All Usage Examples Of System.DateTimeFormat::FormatCustomized