title: DateTime format to SQL format using C#
body: <p>I am trying to save the current date time format from C# and convert it to an SQL Server date format like so <code>yyyy-MM-dd HH:mm:ss</code> so I can use it for my <code>UPDATE</code> query.</p>
  
  <p>This was my first code:</p>
  
  <pre><code>DateTime myDateTime = DateTime.Now;
  string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
  </code></pre>
  
  <p>The output on date is okay, but time is always "12:00:00" so I changed my code to the following:</p>
  
  <pre><code>string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " + 
  myDateTime.TimeOfDay.ToString("HH:mm:ss");
  </code></pre>
  
  <p>It gave me this compile error:</p>
  
  <blockquote>
    <p>FormatException was unhandled</p>
  </blockquote>
  
  <p>And suggested I need to parse. So I tried doing this to my code as per my research here in StackOverflow:</p>
  
  <pre><code>string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " + 
  myDateTime.Parse.TimeOfDay.ToString("HH:mm:ss");
  </code></pre>
  
  <p>or</p>
  
  <pre><code>string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " + 
  myDateTime.tryParse.TimeOfDay.ToString("HH:mm:ss");
  </code></pre>
  
  <p>But it's telling me that it's a method which is not valid for given context. I tried searching for solutions to my problem and I have been stuck for two hours now. I'm still a bit new in C#, can you help me please?</p>