简体   繁体   English

C#+中的DateTime比较日期时间

[英]DateTime In C# + Compare Datetime

  1. I need format type DateTime into: "dd/mm/yyyy". 我需要格式类型DateTime:“dd / mm / yyyy”。
  2. I want to add, sub, compare between 2 DateTime. 我想在2 DateTime之间添加,sub,比较。 ex: 23/12/1991 > 2/1/1990. 例如:23/12/1991> 2/1/1990。 23/12/1991 - 20(days) = 3/12/1991 Could you help me, please.! 23/12/1991 - 20(天)= 3/12/1991请帮助我。 Thank very much.! 非常感谢。! ^^ ^^

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. 任何日期对象都可以与普通的> < <= >=运算符进行比较。

Format: 格式:

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

Add and Sub: Look at the different overload of DateTime.Add and the various others (AddDays, AddHours, etc). 添加和子:查看DateTime.Add和其他各种(AddDays,AddHours等)的不同重载。

Compare: 相比:

dateTime1 - dateTime2

That will return a Timespan. 这将返回Timespan。 You can thus do: 你可以这样做:

(dateTime1-dateTime2).Days >= 20

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: 为了添加/子日期到DateTime对象,使用AddDays()方法:

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

There is also an AddMonths() method that works in the same way. 还有一个以相同方式工作的AddMonths()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM