DateTime In C# + Compare Datetime

  1. I need format type DateTime into: "dd/mm/yyyy".
  2. I want to add, sub, compare between 2 DateTime. ex: 23/12/1991 > 2/1/1990. 23/12/1991 - 20(days) = 3/12/1991 Could you help me, please.! Thank very much.! ^^

Upvotes: 0

Views: 547

Answers (3)

MPelletier
MPelletier

Reputation: 16657

Format:

dateTime.ToString("dd/MM/yyyy");

Add and Sub: Look at the different overload of DateTime.Add and the various others (AddDays, AddHours, etc).

Compare:

dateTime1 - dateTime2

That will return a Timespan. You can thus do:

(dateTime1-dateTime2).Days >= 20

Upvotes: 0

Phil Klein
Phil Klein

Reputation: 7514

To format the string representation if you can do the following:

var date = DateTime.Now;
var dateString = date.ToString("dd/MM/yyyy");

In order the add/sub days to a DateTime object, use the AddDays() method:

// Subtract 20 days
var date = DateTime.Now;
var twentyDaysAgo = date.AddDays(-20);

There is also an AddMonths() method that works in the same way.

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83358

To get that format use:

yourDate.ToString("dd/MM/yyyy);

To add to a date:

yourDate.AddDays(15);
yourDate.AddMonths(3);

and so on

To subtract from a date

yourDate.AddDays(-12);
yourDate.AddMonths(-3); 

and so on

And any date objects can be compared with the normal > < <= >= operators.

Upvotes: 2

Related Questions