CodeKeep C# Feed Marzo 28th, 2008
Description: A class that helps you to format a time string to a specific format (With meridians, AM/PM or military time)
Link:
http://www.codekeep.net/snippets/411cceb9-39dd-4752-9ac7-e215b1a7dd19.aspxpublic static class TimeFormatter
{
/// <summary>
/// Formats a time string with a meridian (:)
/// </summary>
/// <param name="time">The string representing the time</param>
/// <returns>A properly formatted string that represents a time with meridians</returns>
public static string FormatTimeMeridian(string time)
{
time = time.Trim();
string value = time;
Regex testForAMPMWithoutColon = new Regex("^\\d{0,6}[^:]( ?[aApP][mM]?)$");
Regex testForMilitaryTime = new Regex("(\\:)");
if (testForAMPMWithoutColon.IsMatch(value))
{
string sTime = NumberParser.ParseInt(value).ToString(CultureInfo.InvariantCulture); //parseInt(value,10).toString();
if (value.Substring(0, 1) == "0")
sTime = "0" + sTime;
switch (sTime.Length)
{
case 1: // h
value = value.Substring(0, 1) + ":00" + value.Substring(1);
break;
case 2: // hh
value = value.Substring(0, 2) + ":00" + value.Substring(2);
break;
case 3: // hmm
value = value.Substring(0, 1) + ":" + value.Substring(1);
break;
case 4: // hhmm
value = value.Substring(0, 2) + ":" + value.Substring(2);
break;
case 5: // hmmss
value = value.Substring(0, 1) + ":" + value.Substring(1, 2) + ":" + value.Substring(3);
break;
case 6: // hhmmss
value = value.Substring(0, 2) + ":" + value.Substring(2, 2) + ":" + value.Substring(4);
break;
default:
break;
}
}
else if (!testForMilitaryTime.IsMatch(value))
{
// Military time.
switch (value.Length)
{
case 1: // h
value = value.Substring(0, 1) + ":00";
break;
case 2: // hh
value = value.Substring(0, 2) + ":00";
break;
case 3: // hmm
value = value.Substring(0, 1) + ":" + value.Substring(1, 2);
break;
case 4: // hhmm
value = value.Substring(0, 2) + ":" + value.Substring(2, 2);
break;
case 5: // hmmss
value = value.Substring(0, 1) + ":" + value.Substring(1, 2) + ":" + value.Substring(3, 2);
break;
case 6: // hhmmss
value = value.Substring(0, 2) + ":" + value.Substring(2, 2) + ":" + value.Substring(4, 2);
break;
default:
break;
}
}
return value;
}
const string DefaultTimeFormat = "h:mm AM/PM";
/// <summary>
/// Formats a string representing a time to a specific format
/// </summary>
/// <param name="value">The String representing the Time</param>
/// <param name="format">The format of the return time string</param>
/// <returns>A time string</returns>
public static string FormatToTimeString(string value, string format)
{
// Get the date format.
// If a format was passed, use it, otherwise the default format.
string fmt = String.Empty;
if (String.IsNullOrEmpty(format.Trim()))
fmt = DefaultTimeFormat;
else
fmt = format;
Regex re = new Regex("^(h|hh)(:mm)(:ss)?( am\\/pm| AM\\/PM| a\\/p| A\\/P)?$");
// Use the default format if the provided format is not valid.
if (!re.IsMatch(fmt))
fmt = "h:mm AM/PM";
bool hasMeridian = false;
string[] meridian = "am,pm".Split(',');
Regex regExHasMeridian = new Regex("\\b(am\\/pm|AM\\/PM|a\\/p|A\\/P)\\b");
if (regExHasMeridian.IsMatch(fmt))
{
int meridianLength = 0;
hasMeridian = true;
Regex regExHasLowerCaseMeridian = new Regex("\\bam\\/pm\\b");
Regex regExHasUpperCaseMeridian = new Regex("\\bAM\\/PM\\b");
Regex regExHasOneLetterLowerCaseMeridian = new Regex("a\\/p");
Regex regExHasOneLetterUpperCaseMeridian = new Regex("\\bA\\/P\\b");
if (regExHasLowerCaseMeridian.IsMatch(fmt))
{
meridian = "am,pm".Split(',');
meridianLength = 6;
}
else if (regExHasUpperCaseMeridian.IsMatch(fmt))
{
meridian = "AM,PM".Split(',');
meridianLength = 6;
}
else if (regExHasOneLetterLowerCaseMeridian.IsMatch(fmt))
{
meridian = "a,p".Split(',');
meridianLength = 4;
}
else if (regExHasOneLetterUpperCaseMeridian.IsMatch(fmt))
{
meridian = "A,P".Split(',');
meridianLength = 4;
}
fmt = fmt.Substring(0, fmt.Length - meridianLength);
}
// Initialize time variables.
Regex regExValueHasMeridian = new Regex("[aApP][mM]?$");
string h = "0";
string m = "00";
string s = "00";
string sMeridian = "";
bool valueHasMeridian = regExValueHasMeridian.IsMatch(value);
string sTemp = "";
string[] values = value.Split(':');
string[] fmtItems = fmt.Split(':');
// Go through each item in the value field.
for (int i = 0; i < values.Length; i++)
{
if (i >= fmtItems.Length)
break;
switch (fmtItems[i])
{
case "h":
case "hh":
int iTemp = NumberParser.ParseInt(values[i]);
// Make sure the hours are in 24 hour format.
if (valueHasMeridian)
{
Regex regExIsPM = new Regex("[pP][mM]?$");
Regex regExIsAM = new Regex("[aA][mM]?$");
if (regExIsPM.IsMatch(value))
{
if (iTemp < 12)
iTemp += 12;
}
else if (regExIsAM.IsMatch(value) && iTemp == 12)
{
iTemp = 0;
}
}
// Does the format string expect a Meridian?
// If so put the hours in 12 hour format.
if (hasMeridian)
{
if (iTemp > 12)
{ // pm
iTemp -= 12;
sMeridian = meridian[1];
}
else if (iTemp == 12)
{ // pm
sMeridian = meridian[1];
}
else if (iTemp > 0)
{ // am
sMeridian = meridian[0];
}
else if (iTemp == 0)
{ // am
iTemp = 12;
sMeridian = meridian[0];
}
}
// Format the hours.
if (fmtItems[i] == "h")
{
h = iTemp.ToString(CultureInfo.InvariantCulture);
}
else
{
sTemp = "0" + iTemp.ToString(CultureInfo.InvariantCulture);
h = sTemp.Substring(sTemp.Length - 2, sTemp.Length);
}
break;
case "mm":
// Format minutes.
sTemp = "0" + NumberParser.ParseInt(values[i]).ToString(CultureInfo.InvariantCulture);
m = sTemp.Substring(sTemp.Length - 2, 2);
break;
case "ss":
// Format seconds.
sTemp = "0" + NumberParser.ParseInt(values[i]).ToString(CultureInfo.InvariantCulture);
s = sTemp.Substring(sTemp.Length - 2, 2);
break;
}
}
// Format time string.
if (fmtItems.Length == 2)
return h + ":" + m + (hasMeridian ? " " + sMeridian : "");
return h + ":" + m + ":" + s + (hasMeridian ? " " + sMeridian : "");
}
}