Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
16:03:19.0830000
I store this in my db as time(7) , I want the time to appear in 4:03pm . Not like this. I use this method but failed, string is not a valid datetime
C#
string timeFromFormat = "hh:mm tt";
DateTime timeFrom = DateTime.ParseExact(tb_TimeFrom.Text, timeFromFormat, CultureInfo.InvariantCulture);
Posted
Updated 31-Jan-14 21:17pm
v3
Comments
OriginalGriff 1-Feb-14 3:43am    
Sorry, but that doesn't make a whole lot of sense.
You talk about a DB but there is no obvious DB code there, just an attempt to convert from a string to a DateTime, using a very specific format - which your example value does not match. And there is no presentation of dates or time involved: you just try to create a DateTime which you can't display directly.

Please edit your question, and try to explain in fuller details what you are trying to do, what you are inputting, and what you are expecting as an output.
Use the "Improve question" widget to edit your question and provide better information.
Member 10548723 1-Feb-14 3:55am    
i store as time(7) , what does (7) means?

The string data you show is not a DateTime: it's a TimeSpan. To convert a TimeSpan into a usable representation of a point in time, you have to do something like this:
private void TestConversion()
{
    string dbDataString = "16:03:19.0830000";
    
    // match the format of the TimeSpan in the Database
    string timeFromFormat = "hh\\:mm\\:ss\\.fffffff";
    
    // output format
    string simpleAMPM = "{0:h:mm tt}";
    
    // convert to TimeSpan
    TimeSpan ts = TimeSpan.ParseExact(dbDataString, timeFromFormat, CultureInfo.InvariantCulture);
    
    // add the TimeSpan to a DateTime
    DateTime theDate = new DateTime() + ts;
    
    // format the result
    string theTime = string.Format(simpleAMPM, theDate);
    
    // check output ...
    Console.WriteLine(theTime);
}
 
Share this answer
 
Comments
Member 10548723 1-Feb-14 5:14am    
how to i get from the textbox value
Please try is as below.

DateTime myDate = DateTime.ParseExact("16:03:19,083", "HH:mm:ss,fff",
                          System.Globalization.CultureInfo.InvariantCulture);
 
        Console.WriteLine(myDate.ToString("hh:mm tt"));


LIVE DEMO :
ideone
 
Share this answer
 
string timeFromFormat = "hh:mm tt";is wrong.
It should be string timeFromFormat = "hh:mm:tt";
 
Share this answer
 
Comments
BillWoodruff 1-Feb-14 8:03am    
"hh:mm tt" is not wrong if it's used on a DateTime ! But, in this case what the OP has is a TimeSpan, not a DateTime. See my answer below.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900