Hi all

I want to create a method that converts from one time or date format (as a string) to another by specifying the inputformat and the outputformat. I can do the output as below but I'm struggling on how to specify what the input format is. Can anyone help?
thanks.

//I'm halfway there.
string date = FormatDateTime(myDate, "yyyyMMdd"));
string time = FormatDateTime(myTime, "HHmm"));


        private string FormatDateTime(string dateortime, string outputformat)
        {
            string ret = "";
            if (dateortime == "")
                return "";
            try
            {
                ret = System.Convert.ToDateTime(dateortime).ToString(outputformat);
            }
            catch
            {
            }
            return ret;
        }

Use a DateTime to do it.
As an example look at this.

Use DateTime.TryParseExact

SUMMARY:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.

commented: gave more than a link :-) +2

DateTime.TryParseExact is exactly what I need. Works perfectly :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.