How can I convert DateTime.now in C # to yyyy-mm-dd hh: mm: ss.sssssss?

I store in my database, using the storage procedure, the date stamp using a function called sysdatetime() and the type varchar(max) , which is stored in the database in this format yyyy-mm-dd hh:mm:ss.sssssss . When I create a new post, it’s fine, but when I try to update the record, I need to send the parameter to the storage procedure using the current datetime . I tried this

 DateTime.Now.ToString(yyyy-mm-dd hh:mm:ss.sssssss) 

but I get an error. what should I do?

Ps: see image below with error message

enter image description here

+6
source share
3 answers

I suspect you really need a string representation, you really want:

 string text = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff", CultureInfo.InvariantCulture) 

Note that:

  • If you really don't want local time, use UtcNow instead of Now . For timestamps, you almost always want UTC.
  • I doubt that you want to use the time separator of the current culture, so the CultureInfo.InvariantCulture specification
  • β€œMM” means months, while β€œmm” means minutes
  • β€œHH” means a 24-hour clock, while β€œhh” means a 12-hour clock.
  • "ff ..." is used for fractions of a second

For more information on custom date and time formatting, see MSDN .

However, I would strongly recommend that you try to avoid string conversions where possible. Why can't your stored procedure use only the appropriate DateTime type instead of a string representation? You can then pass the value to the stored procedure as a DateTime (via the command parameter), and you can get rid of randomly iterating over strings.

+21
source

Use this code:

 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff") 

See this ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+5
source

Here is a small example:

 DateTime date3 = new DateTime(2008, 1, 1, 0, 30, 45, 125); Console.WriteLine("Date with milliseconds: {0:MM/dd/yyy hh:mm:ss.fff}", date3); // Displays the following output to the console: // Date with milliseconds: 01/01/2008 12:30:45.125 

Just put the appropriate amount of "f" in your team and you are done

0
source

Source: https://habr.com/ru/post/914317/


All Articles