Regarding the DateTime format "% h:% m:% s", allowing an hour like "00",

I have a TextBox to enter the time in a format "%h:%m:%s". Allowed temporary inputs:

1:20:00

12:20:00

I am converting a string taken from a TextBox using:

DateTime.TryParseExact("00:20:00", "%h:%m:%s",
                       culture, DateTimeStyles.None, out newData);

But the above code converts the hour 00in 12when providing data through newData. I want to make a mistake in this case. Please enter your details.

+4
source share
2 answers

It seems that you should try to analyze TimeSpaninstead DateTime.

Use the following template string.Formatto convert to TimeSpan:

var pattern = @"hh\:mm\:ss";

. MSDN : http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx

:

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime newData;
            TimeSpan newSpan;

            DateTime.TryParseExact("00:20:00", "%h:%m:%s",
                   CultureInfo.DefaultThreadCurrentCulture, DateTimeStyles.None, out newData);

            Console.WriteLine(newData);
            // 8/5/2014 12:20:00 AM

            TimeSpan.TryParseExact("00:20:00", @"hh\:mm\:ss",
                   CultureInfo.DefaultThreadCurrentCulture, TimeSpanStyles.None, out newSpan);

            Console.WriteLine(newSpan);
            // 00:20:00

            Console.WriteLine(newSpan.Hours);
            // 0 

            Console.WriteLine(newSpan.TotalHours);
            // 0.33~


            Console.ReadLine();
        }
    }
}
+2

"H" 24- .

+1

All Articles