Replacing all instances of UTC time in a string

written by Ryan Olshan on Sunday, February 26 2006

I'm in the progress of upgrading a web application from .NET 1.1 to 2.0 and came across this function that I created which replaces all instances of date/time in a string. In the application users add notes and when it gets saved to the database it appends Added By [User] on [Date/Time] to the end of the notes. The date/time is added as UTC format, so I had to come up with a way to replace each instance of date/time to the users local time when the notes are viewed. Here's how I did it:

using System;

using System.Text.RegularExpressions;

 

public class TimeZoneConversionHelper

{

   public static string RegexReplaceTime(string input, double timeZone)

   {

      string convertedText = String.Empty;

      if ((input != String.Empty) && (input != null))

      {

        string pattern = @"\?*(((((0[13578])|([13578])|(1[02]))[\-\/\s]?\b((0[1-9])|([1-9])|([1-2][0-

9])|(3[01])))|((([469])|(11))[\-\/\s]?\b((0[1-9])|([1-9])|([1-2][0-9])|(30)))|((02|2)[\-\/\s]?\b((0[1-

9])|([1-9])|([1-2][0-9]))))[\-\/\s]?\b\d{4})(\s(((0[1-9])|([1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5]

[0-9])\s))([AM|PM|am|pm]{2,2})))?";

 

        MatchCollection matchCollection = Regex.Matches(input, pattern);

 

        foreach (Match match in matchCollection)

        {

            DateTime conversionDateTime = TimeZoneConversion(Convert.ToDateTime(match.Value), timeZone);

            convertedText = input.Replace(match.ToString(), conversionDateTime.ToString());

        }

      }

 

      return convertedText;

   }

 

   public static DateTime TimeZoneConversion(DateTime utcTime, double timeZone)

   {

      return utcTime.AddHours(timeZone);

   }

}

Kick this post on .NET Kicks

Similar Posts

  1. August 23, 2007 Ask An Expert Live Chat Experts
  2. Implicit and Explicit Operators in C#
  3. 911 Pigeon Alert

Post a comment