1

I have a variable testDate which contains value {01/02/2016 AM 12:00:00}. I need to get only date part from the set. For that I used below code:

var testDate = startDate.AddDays(i);
var testDateOnly = testDate.Date;

But it returns the same {01/02/2016 AM 12:00:00}.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Limna
  • 401
  • 10
  • 28
  • 10
    That's because the .NET `DateTime` datatype *always* has a time component...... there's no `Date` datatype with just the date – marc_s Mar 14 '16 at 05:32
  • Checkout this msdn link https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx – TusharJ Mar 14 '16 at 05:33
  • Duplicate question Please follow [extract the date part from DateTime in C#](http://stackoverflow.com/questions/7740458/extract-the-date-part-from-datetime-in-c-sharp) – Syamesh K Mar 14 '16 at 05:38
  • 1
    Possible duplicate of [How to remove time portion of date in C# in DateTime object only?](http://stackoverflow.com/questions/6121271/how-to-remove-time-portion-of-date-in-c-sharp-in-datetime-object-only) – Smit Patel Mar 14 '16 at 06:21

3 Answers3

4

The date variable will contain the date, the time part will be 00:00:00

http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx

// The date with time component
var testDate = startDate.AddDays(i);

// Get date-only portion of date, without its time (ie, time 00:00:00).
var testDateOnly = testDate.Date;

// Display date using short date string.
Console.WriteLine(testDateOnly.ToString("d"));

// OUTPUT will be     1/2/2016
Syamesh K
  • 826
  • 8
  • 18
0
  var testDate = startDate.AddDays(i);
  string dateOnlyString = testDate.ToString("dd-MM-yyy");

"dd-MM-yyy" this will be the Date Format of the output string, You can choose the format as per your requirements. You can use the following also for formatting:

  dateOnlyString = d.ToString("M/d/yyyy");              // "3/9/2008"
  dateOnlyString = d.ToString("MM/dd/yyyy}");           // "03/09/2008"

  // day/month names
  dateOnlyString = d.ToString("ddd, MMM d, yyyy}");    // "Sun, Mar 9, 2008"
  dateOnlyString = d.ToString("dddd, MMMM d, yyyy}");  // "Sunday, March 9,2008"

  // two/four digit year
  dateOnlyString = d.ToString("MM/dd/yy}");           // "03/09/08"
  dateOnlyString = d.ToString("MM/dd/yyyy}");         // "03/09/2008"
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

You need to convert the Date in to String type using this,

var testDate = startDate.AddDays(i);

var testDateOnly = testDate.Date.ToShortDateString(); //string

or

var testDateOnly = testDate.Date.ToString("dd/MM/yyyy");

or

var testDateOnly = testDate.Date.ToString("d"); 

Check it here. Find the more about Standard Date and Time Format Strings

You will get the dd-MM-yyyy format by doing this.

Smit Patel
  • 2,992
  • 1
  • 26
  • 44