A quick post about probably the most used piece of code I have in my toolbox. First, the problem:

I have many functions where I need to merge in date and time into a string. Stuff like creating log files. Let’s say I want a daily log file named according to a format I have in a configuration file.

<add key=”LogFileNamevalue=”log-[MM]-[DD]-[YYYY].log/>

string filename = ConfigurationManager.AppSettings[“LogFileName”];

So, I write out to a log file for the current date. Sounds pretty easy. What if, however, I was looking in an FTP site for a file named for YESTERDAY? Now we are getting a tiny bit more complicated. I can imagine for that merge string I would want something like “incoming-[MM]-[DD-1]-[YYYY].csv” for example.

I came upon this problem so often that I felt it necessary to create a method for it, called GetDateMerge that took in a string, did all the replaces, and then returned the result. The call looked like:

string _strFileName = GetDateMerge(ConfigurationManager.AppSettings[“LogFileName”]);

I used it like that for years. Then one of my programmers decided it would be more elegant as an extension method. Basically, now it was a method ON the string class, just like “Trim()” and “Length()”. We changed the name, and take in an optional date (defaulting to DateTime.Now) by overloading the method. Now the call looks more like:

string _strFileName = ConfigurationManager.AppSettings[“LogFileName”].GetMergeString();

It’s a bit more sexy that way. Here is the complete code for the method (and the overload):

#region merge string
        public static string GetMergeString(this string obj)
        {
            return GetMergeString(obj, DateTime.Now);
        }

        public static string GetMergeString(this string obj, DateTime MergeDate)
        {
            Regex monthShortRE = new Regex("\\[MM.*?\\]");
            Regex monthMidRE = new Regex("\\[MMM.*?\\]");
            Regex monthLongRE = new Regex("\\[MMMM.*?\\]");
            Regex dayRE = new Regex("\\[DD.*?\\]");
            Regex yearShortRE = new Regex("\\[YY.*?\\]");
            Regex yearLongRE = new Regex("\\[YYYY.*?\\]");
            Regex hourRE = new Regex("\\[hh.*?\\]");
            Regex minuteRE = new Regex("\\[mm.*?\\]");
            Regex secondRE = new Regex("\\[ss.*?\\]");
            Regex millisecondRE = new Regex("\\[ms.*?\\]");

            string monthMatch = "";
            string yearMatch = "";
            string dayMatch = "";
            string hourMatch = "";
            string minuteMatch = "";
            string secondMatch = "";
            string millisecondMatch = "";

            if (monthShortRE.IsMatch(obj))
            {
                monthMatch = monthShortRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (dayRE.IsMatch(obj))
            {
                dayMatch = dayRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (yearLongRE.IsMatch(obj))
            {
                yearMatch = yearLongRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }
            else if (yearShortRE.IsMatch(obj))
            {
                yearMatch = yearShortRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (hourRE.IsMatch(obj))
            {
                hourMatch = hourRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (minuteRE.IsMatch(obj))
            {
                minuteMatch = minuteRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (secondRE.IsMatch(obj))
            {
                secondMatch = secondRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            if (millisecondRE.IsMatch(obj))
            {
                millisecondMatch = millisecondRE.Match(obj).ToString().Trim(new char[] { '[', ']' });
            }

            DateTime dt = MergeDate;
            char[] ops = new char[] { '+', '-' };

            if (!string.IsNullOrEmpty(monthMatch) && monthMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(monthMatch.Split(ops)[1]);

                if (monthMatch.Contains("-"))
                {
                    dt = dt.AddMonths(-1 * opValue);
                }
                else if (monthMatch.Contains("+"))
                {
                    dt = dt.AddMonths(opValue);
                }
            }

            if (!string.IsNullOrEmpty(dayMatch) && dayMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(dayMatch.Split(ops)[1]);

                if (dayMatch.Contains("-"))
                {
                    dt = dt.AddDays(-1 * opValue);
                }
                else if (dayMatch.Contains("+"))
                {
                    dt = dt.AddDays(opValue);
                }
            }

            if (!string.IsNullOrEmpty(yearMatch) && yearMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(yearMatch.Split(ops)[1]);

                if (yearMatch.Contains("-"))
                {
                    dt = dt.AddYears(-1 * opValue);
                }
                else if (yearMatch.Contains("+"))
                {
                    dt = dt.AddYears(opValue);
                }
            }

            if (!string.IsNullOrEmpty(hourMatch) && hourMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(hourMatch.Split(ops)[1]);

                if (hourMatch.Contains("-"))
                {
                    dt = dt.AddHours(-1 * opValue);
                }
                else if (hourMatch.Contains("+"))
                {
                    dt = dt.AddHours(opValue);
                }
            }

            if (!string.IsNullOrEmpty(minuteMatch) && minuteMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(minuteMatch.Split(ops)[1]);

                if (minuteMatch.Contains("-"))
                {
                    dt = dt.AddMinutes(-1 * opValue);
                }
                else if (minuteMatch.Contains("+"))
                {
                    dt = dt.AddMinutes(opValue);
                }
            }

            if (!string.IsNullOrEmpty(secondMatch) && secondMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(secondMatch.Split(ops)[1]);

                if (secondMatch.Contains("-"))
                {
                    dt = dt.AddSeconds(-1 * opValue);
                }
                else if (secondMatch.Contains("+"))
                {
                    dt = dt.AddSeconds(opValue);
                }
            }

            if (!string.IsNullOrEmpty(millisecondMatch) && millisecondMatch.Split(ops).Length > 1)
            {
                int opValue = Convert.ToInt32(millisecondMatch.Split(ops)[1]);

                if (millisecondMatch.Contains("-"))
                {
                    dt = dt.AddMilliseconds(-1 * opValue);
                }
                else if (millisecondMatch.Contains("+"))
                {
                    dt = dt.AddMilliseconds(opValue);
                }
            }

            if (monthShortRE.IsMatch(obj))
            {
                obj = monthShortRE.Replace(obj, dt.Month.ToString().PadLeft(2, '0'));
            }
            else if (monthMidRE.IsMatch(obj))
            {
                string monthName = dt.ToString("MMM", CultureInfo.InvariantCulture).ToUpper();
                obj = monthMidRE.Replace(obj, monthName);
            }
            else if (monthLongRE.IsMatch(obj))
            {
                string monthName = dt.ToString("MMMM", CultureInfo.InvariantCulture);
                obj = monthLongRE.Replace(obj, monthName);
            }

            obj = dayRE.Replace(obj, dt.Day.ToString().PadLeft(2, '0'));
            if (yearLongRE.IsMatch(obj))
            {
                obj = yearLongRE.Replace(obj, dt.Year.ToString().PadLeft(4, '0'));
            }
            else if (yearShortRE.IsMatch(obj))
            {
                obj = yearShortRE.Replace(obj, dt.Year.ToString().Substring(2).PadLeft(2, '0'));
            }
            obj = hourRE.Replace(obj, dt.Hour.ToString().PadLeft(2, '0'));
            obj = minuteRE.Replace(obj, dt.Minute.ToString().PadLeft(2, '0'));
            obj = secondRE.Replace(obj, dt.Second.ToString().PadLeft(2, '0'));
            obj = millisecondRE.Replace(obj, dt.Millisecond.ToString().PadLeft(2, '0'));

            return obj;
        }
        #endregion

Enjoy this little tool!

Advertisements