none
Convert date time - Time standards issue RRS feed

  • Question

  • Hi,

    I am converting a datetime from one format to another format

    strInputDate = "Wed Dec 4 16:20:01 IST 2013";
    inputFormat = "ddd MMM d HH':'mm':'ss IST yyyy";
    ouputFormat = "MMM  d HH:mm:ss";
    
    DateTime.ParseExact(strInputDate, inputFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(ouputFormat);
    
    The above code works fine
    
    ________________________________________________________________________
    
    But the same code wont work for the below inputs
    
    strInputDate = "Wed Dec 4 16:20:01 UTC 2013";
    inputFormat = "ddd MMM d HH':'mm':'ss IST yyyy";
    ouputFormat = "MMM  d HH:mm:ss";
    
    DateTime.ParseExact(strInputDate, inputFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(ouputFormat);


    The reason is that input string contains 'UTC' instead of 'IST'. But the input date format specifies it as 'IST'.
    Is there a better way to convert this datetime format irrespective of time standards(UTC, IST etc)? The input string may contain anything, it is not going to be always UTC or IST etc....

    Thursday, March 14, 2013 6:32 AM

Answers

  • I'm not saying the code below is pretty, but it works.  I used REgEx to get the Time Zone and then changed the input format to include the proper Time Zone.

    System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strInputDate = "";
                string inputFormat = "";
                string ouputFormat = "";
                string output = "";
                Regex pattern = new Regex(@"\w+");
                string timeZone = "";
                MatchCollection parseResults;
                strInputDate = "Wed Dec 4 16:20:01 IST 2013";
                parseResults = pattern.Matches(strInputDate);
                timeZone = parseResults[6].ToString();
                inputFormat = string.Format("ddd MMM d HH':'mm':'ss {0} yyyy", timeZone);
                ouputFormat = "MMM  d HH:mm:ss";
                output = DateTime.ParseExact(strInputDate, inputFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(ouputFormat);
                strInputDate = "Wed Dec 4 16:20:01 UTC 2013";
                parseResults = pattern.Matches(strInputDate);
                timeZone = parseResults[6].ToString();
                inputFormat = string.Format("ddd MMM d HH':'mm':'ss {0} yyyy",timeZone);
                ouputFormat = "MMM  d HH:mm:ss";
                output = DateTime.ParseExact(strInputDate, inputFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(ouputFormat);
            }
        }
    }


    jdweng

    Thursday, March 14, 2013 9:59 AM