-4

I have null able DateTime database field and its corresponding class's DateTime? variable in C# code.

I want to convert that value in normal date.

e.g. I want to convert From

2013-12-12 00:00:00.000 to 2013-12-12

Any help is admirable. Thanks.

sapatelbaps
  • 484
  • 2
  • 8
  • 19
  • For `DateTime`s "2013-12-12 00:00:00.000" is "2013-12-12" - i.e. they have the same value, but different representations as strings – Rowland Shaw Dec 05 '13 at 10:09
  • possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – sapatelbaps Dec 05 '13 at 10:22

7 Answers7

4
if(dt.HasValue)
{
    newDt = dt.Value.ToString("yyyy-MM-dd");
}

I suppose that dt is the value you get from your database. If it is not null, then I set the string newDt equal to the expression you want.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

It's just unclear what do you mean by "normal" date, but I assume you want to format it in a proper way. DateTime object extends the ToString() method to provide format information:

DateTime? dt;
//your code here
string output;
if (dt != null){
  output = ((DateTime)dt).ToString("yyyy'-'MM'-'dd");
}
LittleSweetSeas
  • 6,786
  • 2
  • 21
  • 26
1

You can use the DateTime.Parse(String) in combination with .ToShortDateString().

So for your example:

DateTime.Parse("2013-12-12 00:00:00.000").ToShortDateString()

Its without catching a ParseException or something else, so you have to do it by yourself!

Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
Inoir
  • 11
  • 1
0

You can try ToShortDateString() method

yourDate.ToShortDateString();

with yourDate a DateTime varible.
It will remove the time part of your datetime (ie 00:00:00.000) and only keep the Date part.

AlexB
  • 7,302
  • 12
  • 56
  • 74
0
DateTime dateToDisplay = new DateTime(2009, 6, 1, 8, 42, 50);
String formattedDate = dateToDisplay.ToShortDateString()

You can also set the culture here to get in whatever format you want.

http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring(v=vs.110).aspx

Pankaj
  • 2,618
  • 3
  • 25
  • 47
0

var s = ((DateTime)ExpirtyDate).Date; string ans = s.ToString()

sapatelbaps
  • 484
  • 2
  • 8
  • 19
0

Take the value in a datetime variable and use the following to just get the date and not time:

DateTime Mydate = DateTime.Now;// instead of datetime.now get the value form sql 



DateTime newformat = Mydate.Date;//then use this to get only date and remove tome 

alternatively you can use the mydate.ToShortDateString() function as well

slecorne
  • 1,720
  • 1
  • 11
  • 14
Ezio
  • 1
  • 1