Currently, I’m returning feedback to the user in this form:
"<UserName> removed 07:00, 07:15, 07:30, 07:45, 08:00, 08:15, 08:30, 09:00, 09:15, 09:30, 09:45, 10:00, 10:15, 10:30, 11:15, (etc.)"
…Understandably, they want it to be more user-friendly, such as this instead:
<UserName> removed 07:00 - 8:30, 9:00 - 10:30, 11:15 - (etc.)
Rather than rework the whole method that concatenates these values into a StringBuilder, I’d like to take that first output and morph it into the second; something like:
sbQuarterHoursRemoved = CombineSucceedingQuarterHours(sbQuarterHoursRemoved);
Is this as tedious as it appears to me, or does somebody know a relatively painless way of accomplishing it?
UPDATE
I adapted the code below to this:
String QuarterHoursRemovedPrettified = PrettifyQuarterHoursRemoved(sbQuarterHoursRemoved);
. . .
private static string PrettifyQuarterHoursRemoved(StringBuilder sbQuarterHoursRemoved)
{
string[] times = sbQuarterHoursRemoved.ToString().Split(',');
DateTime prevDt = new DateTime(1);
string prevString = "";
StringBuilder output = new StringBuilder();
foreach (string time in times) {
DateTime dt = DateTime.ParseExact(time, "HH:mm", CultureInfo.InvariantCulture);
if (dt.Subtract(prevDt).TotalMinutes > 15) {
if (prevString != "")
output.Append(" " + prevString + ",");
output.Append(" " + time + " -");
}
prevString = time;
prevDt = dt;
}
output.Remove(output.Length - 1, 1);
return output.ToString();
}
With values in times like this (after the call to Split()):
00:45
01:00
01:15
22:45
23:00
It ALWAYS crashes the second pass through the loop. The first goes fine, but the second time, no matter what value, crashes.
e.g., the first time through, dt becomes:
dt = 6/26/2012 12:45 am
…after the call to ParseExact()
…but the second call to ParseExact() – with, for example, “01:00” as the value in “time” fails.
Some error details are:
*System.FormatException was unhandled
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at TitanNextGen_Platypi.PlatypiMainForm.PrettifyQuarterHoursRemoved(StringBuilder sbQuarterHoursRemoved) in…*
UPDATED AGAIN
It works now – untrimmed vals were the problem. When the value was, for example, ” 01:15″ instead of “01:15” all Dallas broke loose (and I changed “hh:mm” to “HH:mm” in the call to ParseExact() to account for 24-hour time)
As you are processing the strings, you will need to keep track of where you are at and if you need to start a new sequence: