简体   繁体   English

C#中的DateTime.Now以SQL Server数据类型生成Datetime2(3)

[英]DateTime.Now in C# to yield Datetime2(3) in SQL Server datatype

I tried several ways to retrieve datetime2(3) equivalent from C# code but in vain. 我尝试了几种方法从C#代码中检索datetime2(3)等效但是徒劳无功。

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 way, 当我尝试以下方式时,

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

it is throwing following error 它抛出以下错误

String was not recognized as a valid DateTime. 字符串未被识别为有效的DateTime。

I need the date in datetime2(3) format only instead you can suggest me to save as nvarchar . 我只需要datetime2(3)格式的日期,你可以建议我保存为nvarchar But I need to sort the entries according to the datetime2 they were updated. 但是我需要根据更新的datetime2对条目进行排序。

Is there any other way to solve this? 有没有其他方法可以解决这个问题?

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

DateTime is a data type representing dates and times and does not store format information. DateTime是表示日期和时间的数据类型,不存储格式信息。 The milliseconds are always stored in DateTime. 毫秒始终存储在DateTime中。 The only time you need to specify milliseconds is when choosing how to represent the DateTime as another type, like a string. 您需要指定毫秒的唯一时间是选择如何将DateTime表示为另一种类型,如字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM