puffles
puffles

Reputation: 362

How to extract time from Datetime

Im trying to extract time from Datetime and then converting it into int to add 10 to it and then convert it into Datetime and store in the database. But I keep getting following error:

"String was not recognized as a valid DateTime."

Following is the code:

MySqlConnection conn = new MySqlConnection(connection);
            String query = "Select timings from topogen.token_gen order by timings desc limit 0,1;";
            MySqlCommand cmd = new MySqlCommand(query, conn);

            String location = "";
            conn.Open();
            MySqlDataReader r = cmd.ExecuteReader();
            string timings="";

           while( r.Read()){
            timings = r["timings"].ToString();}

           DateTime time = DateTime.Parse(timings); //error appears here
           timings = time.ToString("HH:mm:ss");
           time = DateTime.Parse(timings);



           long  t = time.Ticks;
           t += 10;
           timings = t.ToString("HH:mm:ss");
           TextBox1.Text = timings;
           time = DateTime.ParseExact(timings, "HH:mm:ss", null);
            this.Location = location;
            conn.Close();

Upvotes: 0

Views: 979

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98740

Looks like your r["timings"].ToString() generates a string representation that your CurrentCulture does not have a standard date and time format. That's why your DateTime.Parse throws FormatException.

  1. Change your timings column type to datetime type even it doesn't.
  2. Use GetDateTime() method of MySqlDataReader to get it's value as DateTime

MySqlDataReader r = cmd.ExecuteReader();
if(r.Read())
{
   DateTime timings = r.GetDateTime(0);
}

Let's look the rest of your code. They have also some mistakes.

long  t = time.Ticks;

With this, you will get Ticks of your DateTime which looks like for example; 2,193,385,800,000,000.

t += 10;

With this, you will get 2,193,385,800,000,010 which is okey for now because it is a long and this is just an addition.

timings = t.ToString("HH:mm:ss");

Here a mistake. You try to get string representation of your long which uses NumberFormatInfo of your CurrentCulture. It doesn't even use DateTimeFormatInfo. That's your your timings will be HH:mm:ss as a string. And you will try to parse it as DateTime.ParseExact(timings, "HH:mm:ss", null) which is equal to DateTime.ParseExact("HH:mm:ss", "HH:mm:ss", null). As you can see, this parsing operation will fail.

Consider to changing your logic.

Upvotes: 1

Related Questions