2016-10-04 22 views
0

我必须建立这样的日期时间才能获得增加的日期,因为它应该继续前进。然后我有时间,因为它应该在04/10/16到10/09/16之间出发彼此抵消日期时间 - 必须告诉总共的天数

我不在乎日期时间。它不应该用于任何事情。我需要的是从那时起有多少天。

Datetime dateString = "4/10/2016 8:30:52" //I pretend that it comes from the database, it was more in terms of see what come there. 
DateTime dt = DateTime.Now.AddDays(5); 

我需要的是,它告诉我在我进入的两个日期时间之间有多少天。

+0

*两个日期时间之间有多少天*这里只有*一个*'DateTime' - 另一个是字符串。 – Plutonix

+0

@Plutonix我假装它来自数据库,它更多的是看看那里发生了什么。 –

+0

所有主要数据库都可以存储并返回日期时间。给出2个DateTime值,只需减去 – Plutonix

回答

2

可以DateTime。减去对象获得TimeSpan

Datetime dateString = DateTime.Parse("4/10/2016 8:30:52"); 
DateTime dt = DateTime.Now; 
TimeSpan duration = dt-dateString; 

TimeSpan对象,你可以得到多少(满)天:

int totalCompleteDays = (int)duration.TotalDays; 

或者你想要一个四舍五入的结果:

int roundedTotalDays = (int)Math.Round(duration.TotalDays); 
+1

这将起作用*,但要小心...... *它会在没有任何警告的情况下将天数舍入。这意味着超过3天半的时间会返回为4天! ;) –

+0

True @ timothy-Groote。我认为这是作者想要的,但我可能实际上是错的。我更新了答案;) –

+0

没关系,我认为那也是他想要的。 –

2

DateTime对象支持基本的操作符并将返回TimeSpan对象。

DateTime DateTimeB = DateTime.Now.AddDays(5); 
DateTime DateTimeA = DateTime.Now; 
TimeSpan difference = DateTimeA - DateTimeB; 

... 然后你可以使用TotalDaysproperty of the timeSpan。 ...

Console.out.WriteLine(difference.TotalDays); 
+0

我想你误解了我的问题。这就是我想要的日子,而不是它的时间跨度。 –

+0

我认为你误读我的答案,然后,因为我解释如何获得该时间跨度的天数;) –

+0

噢好吧:)现在我明白现在好多了,现在正确后 –