Limna
Limna

Reputation: 403

To Get Date From DateTime Variable

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}.

Upvotes: 1

Views: 10253

Answers (3)

Smit Patel
Smit Patel

Reputation: 3247

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.

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

  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"

Upvotes: 0

Syamesh K
Syamesh K

Reputation: 826

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

Upvotes: 4

Related Questions