XML Date, Convert to TimeZone

Dates are complicated no matter which language you use.  To solve some of our problems we save all dates as Universal time, typically using (DateTime.UtcNow).  Then when we display it we convert to a specific timezone.

For this specific project we save the Utc date as an XML string.  When we parse it out for display we read the date, convert to the proper timezone, then put it back in the XML be parsed for display. In this system we show all our dates as Central Standard Time.   We were doing a TryParse but got an error stating that the date was the wrong “Kind”.  Finally I hit on the right syntax and, as with so many other little tidbits, don’t want to lose it.


.......

XElement cElement = data.Element("CreatedDate");

cElement.ReplaceWith(GetDateFormattedCst(cElement, "{0:g} CST"));

.......
 private XElement GetDateFormattedCst(XElement element, string format)
    {
      if(element == null || element.IsEmpty)
         return null;
      XmlReader reader = element.CreateReader();
      reader.MoveToContent();
      string dateValue = reader.ReadInnerXml();

      DateTime dateTime;
      CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
      DateTimeStyles styles = DateTimeStyles.AdjustToUniversal;

      if (DateTime.TryParse(dateValue, culture, styles, out dateTime))
      {
        dateTime = dateTime.ToCentralStandardTime();
      }
      else
      {
        return null;
      }

      dateValue = String.Format(format, dateTime);
      dateValue = string.Format("<{0}>{1}</{0}>", element.Name, dateValue);

      return XElement.Parse(dateValue);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s