Home
Manage Your Code
Snippet: TimeFormatter (C#)
Title: TimeFormatter Language: C#
Description: A class that helps you to format a time string to a specific format (With meridians, AM/PM or military time) Views: 327
Author: Berin Iwlew Date Added: 3/28/2008
Copy Code  
1public static class TimeFormatter
2{
3
4    /// <summary>

5    /// Formats a time string with a meridian (:)

6    /// </summary>

7    /// <param name="time">The string representing the time</param>

8    /// <returns>A properly formatted string that represents a time with meridians</returns>

9    public static string FormatTimeMeridian(string time)
10    {
11        time = time.Trim();
12        string value = time;
13
14        Regex testForAMPMWithoutColon = new Regex("^\\d{0,6}[^:]( ?[aApP][mM]?)$");
15        Regex testForMilitaryTime = new Regex("(\\:)");
16
17        if (testForAMPMWithoutColon.IsMatch(value))
18        {
19
20            string sTime = NumberParser.ParseInt(value).ToString(CultureInfo.InvariantCulture); //parseInt(value,10).toString();

21            if (value.Substring(0, 1) == "0")
22                sTime = "0" + sTime;
23            switch (sTime.Length)
24            {
25                case 1:	// h

26                    value = value.Substring(0, 1) + ":00" + value.Substring(1);
27                    break;
28                case 2:	// hh

29                    value = value.Substring(0, 2) + ":00" + value.Substring(2);
30                    break;
31                case 3:	// hmm

32                    value = value.Substring(0, 1) + ":" + value.Substring(1);
33                    break;
34                case 4:	// hhmm

35                    value = value.Substring(0, 2) + ":" + value.Substring(2);
36                    break;
37                case 5:	// hmmss

38                    value = value.Substring(0, 1) + ":" + value.Substring(1, 2) + ":" + value.Substring(3);
39                    break;
40                case 6:	// hhmmss

41                    value = value.Substring(0, 2) + ":" + value.Substring(2, 2) + ":" + value.Substring(4);
42                    break;
43                default:
44                    break;
45            }
46        }
47        else if (!testForMilitaryTime.IsMatch(value))
48        {
49            // Military time.

50            switch (value.Length)
51            {
52                case 1:	// h

53                    value = value.Substring(0, 1) + ":00";
54                    break;
55                case 2:	// hh

56                    value = value.Substring(0, 2) + ":00";
57                    break;
58                case 3:	// hmm

59                    value = value.Substring(0, 1) + ":" + value.Substring(1, 2);
60                    break;
61                case 4:	// hhmm

62                    value = value.Substring(0, 2) + ":" + value.Substring(2, 2);
63                    break;
64                case 5:	// hmmss

65                    value = value.Substring(0, 1) + ":" + value.Substring(1, 2) + ":" + value.Substring(3, 2);
66                    break;
67                case 6:	// hhmmss

68                    value = value.Substring(0, 2) + ":" + value.Substring(2, 2) + ":" + value.Substring(4, 2);
69                    break;
70                default:
71                    break;
72            }
73        }
74
75        return value;
76    }
77
78    const string DefaultTimeFormat = "h:mm AM/PM";
79
80    /// <summary>

81    /// Formats a string representing a time to a specific format

82    /// </summary>

83    /// <param name="value">The String representing the Time</param>

84    /// <param name="format">The format of the return time string</param>

85    /// <returns>A time string</returns>

86    public static string FormatToTimeString(string value, string format)
87    {
88        // Get the date format.

89        // If a format was passed, use it, otherwise the default format.

90        string fmt = String.Empty;
91
92        if (String.IsNullOrEmpty(format.Trim()))
93            fmt = DefaultTimeFormat;
94        else
95            fmt = format;
96        Regex re = new Regex("^(h|hh)(:mm)(:ss)?( am\\/pm| AM\\/PM| a\\/p| A\\/P)?$");
97
98        // Use the default format if the provided format is not valid.

99        if (!re.IsMatch(fmt))
100            fmt = "h:mm AM/PM";
101
102        bool hasMeridian = false;
103        string[] meridian = "am,pm".Split(',');
104
105        Regex regExHasMeridian = new Regex("\\b(am\\/pm|AM\\/PM|a\\/p|A\\/P)\\b");
106
107        if (regExHasMeridian.IsMatch(fmt))
108        {
109            int meridianLength = 0;
110            hasMeridian = true;
111
112            Regex regExHasLowerCaseMeridian = new Regex("\\bam\\/pm\\b");
113            Regex regExHasUpperCaseMeridian = new Regex("\\bAM\\/PM\\b");
114            Regex regExHasOneLetterLowerCaseMeridian = new Regex("a\\/p");
115            Regex regExHasOneLetterUpperCaseMeridian = new Regex("\\bA\\/P\\b");
116
117            if (regExHasLowerCaseMeridian.IsMatch(fmt))
118            {
119                meridian = "am,pm".Split(',');
120                meridianLength = 6;
121            }
122            else if (regExHasUpperCaseMeridian.IsMatch(fmt))
123            {
124                meridian = "AM,PM".Split(',');
125                meridianLength = 6;
126            }
127            else if (regExHasOneLetterLowerCaseMeridian.IsMatch(fmt))
128            {
129                meridian = "a,p".Split(',');
130                meridianLength = 4;
131            }
132            else if (regExHasOneLetterUpperCaseMeridian.IsMatch(fmt))
133            {
134                meridian = "A,P".Split(',');
135                meridianLength = 4;
136            }
137
138            fmt = fmt.Substring(0, fmt.Length - meridianLength);
139        }
140
141        // Initialize time variables.

142        Regex regExValueHasMeridian = new Regex("[aApP][mM]?$");
143        string h = "0";
144        string m = "00";
145        string s = "00";
146        string sMeridian = "";
147        bool valueHasMeridian = regExValueHasMeridian.IsMatch(value);
148        string sTemp = "";
149        string[] values = value.Split(':');
150        string[] fmtItems = fmt.Split(':');
151
152        // Go through each item in the value field.

153        for (int i = 0; i < values.Length; i++)
154        {
155            if (i >= fmtItems.Length)
156                break;
157
158            switch (fmtItems[i])
159            {
160                case "h":
161                case "hh":
162                    int iTemp = NumberParser.ParseInt(values[i]);
163                    // Make sure the hours are in 24 hour format.

164                    if (valueHasMeridian)
165                    {
166                        Regex regExIsPM = new Regex("[pP][mM]?$");
167                        Regex regExIsAM = new Regex("[aA][mM]?$");
168
169                        if (regExIsPM.IsMatch(value))
170                        {
171                            if (iTemp < 12)
172                                iTemp += 12;
173                        }
174                        else if (regExIsAM.IsMatch(value) && iTemp == 12)
175                        {
176                            iTemp = 0;
177                        }
178                    }
179
180                    // Does the format string expect a Meridian?

181                    // If so put the hours in 12 hour format.

182                    if (hasMeridian)
183                    {
184                        if (iTemp > 12)
185                        {			// pm

186                            iTemp -= 12;
187                            sMeridian = meridian[1];
188                        }
189                        else if (iTemp == 12)
190                        {		// pm

191                            sMeridian = meridian[1];
192                        }
193                        else if (iTemp > 0)
194                        {		// am

195                            sMeridian = meridian[0];
196                        }
197                        else if (iTemp == 0)
198                        {		// am

199                            iTemp = 12;
200                            sMeridian = meridian[0];
201                        }
202                    }
203
204                    // Format the hours.

205                    if (fmtItems[i] == "h")
206                    {
207                        h = iTemp.ToString(CultureInfo.InvariantCulture);
208                    }
209                    else
210                    {
211                        sTemp = "0" + iTemp.ToString(CultureInfo.InvariantCulture);
212                        h = sTemp.Substring(sTemp.Length - 2, sTemp.Length);
213                    }
214
215                    break;
216
217                case "mm":
218                    // Format minutes.

219                    sTemp = "0" + NumberParser.ParseInt(values[i]).ToString(CultureInfo.InvariantCulture);
220                    m = sTemp.Substring(sTemp.Length - 2, 2);
221                    break;
222
223                case "ss":
224                    // Format seconds.

225                    sTemp = "0" + NumberParser.ParseInt(values[i]).ToString(CultureInfo.InvariantCulture);
226                    s = sTemp.Substring(sTemp.Length - 2, 2);
227                    break;
228            }
229        }
230
231        // Format time string.

232        if (fmtItems.Length == 2)
233            return h + ":" + m + (hasMeridian ? " " + sMeridian : "");
234
235        return h + ":" + m + ":" + s + (hasMeridian ? " " + sMeridian : "");
236    }
237}
Usage
string myTime = FormatTimeMeridian("1AM"); // returns "1:00 AM"
string myTime2 = FormatTimeMeridian("1830"); // returns "18:30"

string myOtherTime = FormatToTimeString("13:30", "h:mm AM/PM") // returns "1:30 PM"
string myOtherTime2 = FormatToTimeString("1:42:01 PM", "hh:mm:ss") // returns "13:42:01"
Notes
Use this with my NumberParser static class snippet. I really wish there was a COMMENTS SYSTEM. I would love some feedback/comments/suggestions/flames.