9

I tried several ways to retrieve datetime2(3) equivalent 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 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.

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

Is there any other way to solve this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
navule
  • 3,212
  • 2
  • 36
  • 54
  • Maybe you should add some examples and some more details. How do you "store" that date? What type is the database column? – Hans Kesting Jun 19 '12 at 17:59
  • You're trying to save the date and time to a datetime2(3) column in the database? If so, how are you doing it? With a standard `DataSet`, a typed dataset, a command with a dynamcally generated SQL statement and the value concatenated into the string, or a command with parameters? – Steven Doggart Jun 19 '12 at 18:00
  • @ both: I want to insert DateTime.Now in to the Sql datatype of datetime2(3). By using Fluent NHibernate I want to implement it. – navule Jun 19 '12 at 18:06
  • Check out this: http://stackoverflow.com/questions/2033630/datetime-precision-in-nhibernate-and-support-for-datetime2-in-nhibernate-schemee – Steven Doggart Jun 19 '12 at 18:09

1 Answers1

20
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. The milliseconds are always stored in DateTime. The only time you need to specify milliseconds is when choosing how to represent the DateTime as another type, like a string.

Kevin Aenmey
  • 13,259
  • 5
  • 46
  • 45
  • 1
    6/19/2012 11:39:10 PM This is what I got as result Kevin. – navule Jun 19 '12 at 18:11
  • 1
    When you say you "got 6/19/2012 11:39:10 PM", where do you see that value? In the debugger? Console? Whatever is displaying the DateTime value is applying the formatting. The milliseconds are still stored in the value. – Kevin Aenmey Jun 19 '12 at 18:18
  • Ok I got the point. I've seen it in Console. But it worked man. It got saved in Database. Thanks. I could have given u +1 but I don't have enough points. Thanks anyway. – navule Jun 19 '12 at 18:31