DateTime.Now in C # to get Datetime2 (3) in SQL Server data type

I tried several ways to get the equivalent datetime2(3)from C # code, but in vain.

One of them is as follows.

DateTime dt = DateTime.Now.AddMilliseconds(DateTime.Now.Millisecond);

I need the following format:

YYYY-MM-DD HH:MM:SS.FFF

But from the above code, I got the following result

6/19/2012 11:15:08 PM

When I tried the following method,

 string myTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
 DateTime dd = Convert.ToDateTime(myTime);

he throws the following error

The string was not recognized as a valid DateTime.

I only need the date in format datetime2(3), instead you can suggest me save as nvarchar. But I need to sort the entries according to datetime2which they updated.

Is there any other way to solve this problem?

+5
source share
1 answer
var format = "yyyy-MM-dd HH:mm:ss:fff";
var stringDate = DateTime.Now.ToString(format);
var convertedBack = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);

DateTime - , . DateTime. , , , DateTime , .

+14

All Articles