0

found this today:

 DateTime myDateTime = Convert.ToDateTime("1972-12-12 12:12:12");
 Debug.WriteLine(myDateTime);    // shows '12/12/1972 12:12:12'
 String myString = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
 Debug.WriteLine(myString );     // shows '1972.12.12 00:00:00'

minutes gone? why is that?

user26676
  • 280
  • 3
  • 21
  • 7
    What do you think [`myDateTime.Date`](http://msdn.microsoft.com/en-us/library/vstudio/system.datetime.date(v=vs.100).aspx) returns? – GSerg Apr 09 '14 at 08:48
  • 1
    @user26676 [Here's a hint](http://msdn.microsoft.com/en-us/library/system.datetime.date(v=vs.110).aspx). Picnic error, move along people. – Adam Houldsworth Apr 09 '14 at 08:49
  • should be `myDateTime.ToString("yyyy-MM-dd HH:mm:ss");` – kelsier Apr 09 '14 at 08:49
  • not according to this http://stackoverflow.com/questions/3633262/convert-datetime-for-mysql-using-c-sharp – user26676 Apr 09 '14 at 08:50
  • @user26676 How is that question pertinent to this one? – Adam Houldsworth Apr 09 '14 at 08:52
  • seriously... do you guys ever like other people - took <1 minute to get a flood of rage from far too many gloaters? @AdamHouldsworth ? a) read the link and b) thanks (no thanks) for the "help" – user26676 Apr 09 '14 at 08:54
  • @user26676 Well, the link is about conversion from given formats, which isn't the same topic as why you are losing the time element. And my "help" was the official documentation for the `myDateTime.Date` property that you were using and expecting different output for. Your assumptions were incorrect. There is no rage from me, just a comical observation that the bug is not in the `DateTime` implementation, affectionately termed "problem in chair, not in computer". Tim has vocalised and even quoted that very same documentation link as an answer to your problem. – Adam Houldsworth Apr 09 '14 at 08:57

4 Answers4

4

You're using the Date property which truncates the time part here:

String myString = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");

So this gives the desired result:

String myString = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");

MSDN:

A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Try this

myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
0

If you want to compare a DateTime instance to any other date, for example to check if myDateTimeInstance == DateTime.Today, then you need to eliminate the time-part of the DateTime instance.

That is the purpose of myDateTimeInstance.Date: To return only the date, so it can be used while ignoring time.

Kjartan
  • 18,591
  • 15
  • 71
  • 96
0

The problem is you get only the Date part of DateTime. If you want desired value change

String myString = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");

to

String myString = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
Reza
  • 18,865
  • 13
  • 88
  • 163