Difference between 2 DateTimes in Hours? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Showing Difference between two datetime values in hours
Hi,
is there an easy way to get the difference between 2 DateTime-Values in Hours?
I know, its a possibility to calculate itself by get for each day difference 24h, for each month 188h and so on... but is there an easy way given mybe?
Example:
1) 01.02.2010 12:00
2) 03.03.2011 14:00
= ? Hours differnce

It's pretty simple:
TimeSpan diff = secondDate - firstDate;
double hours = diff.TotalHours;
Note that if these DateTime values have been taken locally, the results may not be the number of elapsed hours. For example, you could have one DateTime of midnight and one of 2am, but only one hour had elapsed - because the clocks went forward at 1am. This may or may not be an issue for you. It won't be a problem if you're dealing with UTC DateTime values.

(dateTime1-dateTime2).TotalHours will give a double with the total difference in hours between the two.

date1.Subtract(date2).TotalHours

TimeSpan difference = firstDateTime - secondDateTime;
double diffInHours = difference.TotalHours

DateTime.Subtract(DateTime) will return a TimeSpan that has a TotalHours property.

Related

Calculate hour difference between given date and current date in C#

I want to check to see how many hours difference there are between a given date and the current date. I'm looking for a date that's less then 24 hours away!
I thought this would work but it's giving me a true statement when the EventDateTime is Sunday which is greater then 24 hours out!
bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).Hours < 24 ? true : false;
you want the TotalHours property rather than Hours:
bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).TotalHours < 24;
Try (spaceEvent.EventDateTime - DateTime.Now).TotalHours.
It gives you all the hours distance between two dates
Use .TotalHours
(spaceEvent.EventDateTime - DateTime.Now).TotalHours < 24
put that inside Math.Abs() if you want the proximity of 24 hour regardless which time is first
Use DateTimeOffset instead of DateTime so that time zones don't mess up your math.

Comparing datetimes in eval to hours

I've got a datetime and I want to check if there is 24 hours difference between those two. I just don't know how to do that.
So far I've got this:
<%# (DateTime.Now - Convert.ToDateTime(Eval("new_date"))) < 24 ? "Today" : Eval("new_date") %>
It does not work tho :<
#Edit
And this is how datetime in my database looks like for example:
2016-09-18 12:26:14
The difference between 2 DateTimes is a TimeSpan, which has a TotalDays property you could compare to 1..
The result oft subtracting two DateTime values is a TimeSpan which has properties for hours, minutes, etc.
If you've got two DateTime values you can check whether the difference between them is less than 24 hours like this:
(DateTime.Now - otherDateTime).TotalHours < 24

How to get date after 12 months in c#

I have been given a task to get future date. I mean if today is 1/1/2016 (1st Jan,2016) and when i add 12 months to it then normally it gives 1/1/2017 if i do like this code :
dateTimeObj="1/1/2016"
string futureDate=dateTimeObj.AddMonth(12);
Now this future date will give 1/1/2017 using this code but i have been asked to get when we add 12 months then it must give 12/31/2016 (31 dec,2016) (not 1/1/2017)
How to achieve this ? Is there any inbuilt function to do this, If not then how to do it programtically?
Note: The software on which i am coding is for accounts, they need the date this way only.
I think you should do this
dateTimeObj.AddYears(1).AddDays(-1);
I think there is no special Feature. Just so something like this:
date.AddMonths(12).AddDays(-1);
best regards
When adding 12 months to today, the expected result is same date in next year. So what you have to do is subtract a timespan of one day from it. You can try the above methods in the comments or you can follow this.
This is giving the expected result as 12-31-2016
var dateTimeString = "1/1/2016";
DateTime dateTimeObj = DateTime.Parse(dateTimeString);
DateTime futureDate = dateTimeObj.AddMonths(12).Subtract(TimeSpan.FromDays(1));
Console.WriteLine(futureDate.ToString("MM/dd/yyyy"));
Console.ReadLine();

Why does TimeSpan not have a Years property?

I was writing a converter that takes a person's date of birth and produces their age in years. I wrote something that looked like this:
public class DateOfBirthToAgeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var date = value as DateTime?;
if (date == null) return null;
return (DateTime.Now - date).Years;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I found that there is no Years property on the TimeSpan that results from the subtraction of two DateTime objects. I was somewhat surprised by this. I thought about why there might not be a Years. I figured that it might be because of the leap day, but by that logic, there shouldn't be Days because of daylight savings.
The absence of Months made sense, since there is no standard month length.
I was able to write some different code to get the correct age, but I still really want to know why there is no Years or Weeks property on TimeSpan. Does anyone know the reason?
A TimeSpan only contains the difference between two DateTime values. It is unknown which year this TimeSpan is in. That's also why it doesn't have a Months property.
Example:
TimeSpan.FromDays(60)
How many months are that? 1 or 2?
The absence of Months made sense since there is no standard month length.
There is no standard year length either because of leap years.
Workaround: If you really want to display an approximate value, then doing TimeSpan.TotalDays / 365.2425 will do just fine.
Edit: But only for rough estimations and not for birthdays. In birthday calculation, leap days will accumulate every 4 years as pointed out by Henk Holterman in the comments. Take a look here for calculation of birthdays.
Programmer's life is really hard.
The length of year is variable. Some years have 365 days and some have 366 days. According to the calendar, some years could even have missing days. If talking about culture it becomes more difficult since Chinese lunar calendar can have 13 months a year.
The length of month is variable, and this is well-known. This is also to know that in other calendars things can get worse.
The length of day is variable, because of daylight savings and this is not just culture dependent but also geography dependent.
The length of hour and minute are variable, because of leap seconds.
It seems the only thing that is reliable is the length of a second. So internally, timespan is stored in seconds (or milliseconds, which is the same).
But the variability of time units makes the answer "how many (years/months/days/hours/minites) for n seconds?" being always inaccurate.
This is why the developers end up with a solution that is useful in practical but not precise. They simply ignore daylight savings and leap seconds. However, since people hardly ask about years and months, they just decided not to answer those questions.
Rhetorical question: Without a point of reference, how long is a year?
Because a TimeSpan does not have a fixed point in time, it is not possible to unambiguously say how long a year at an unknown time will be. In the simplest case, it might be 365 or 366 days. There are considerably more cases that would affect the outcome.
I figured that it might be because of the leap day, but by that logic,
there shouldn't be Days because of daylight savings.
You have a point there; subtracting two dates doesn't handle daylight savings ideally. If the dates are local time, you may get an unexpected result.
A change in daylight savings time means a gap or overlap in the local time, and that is ignored if you do calculations with the dates. So, if you want to get the exact difference between two DateTime values that are local time, you should convert them to UTC first as that has linear time:
TimeSpan diff = date1.ToUniversalTime() - date2.ToUniversalTime();
The reason that the TimeSpan doesn't have years is that years differ in length. The daylight savings issue is an effect of how you calculate the TimeSpan and can be circumvented, but there is no "linear years" that you can use to circumvent leap years.
Timespan simply stores number of milliseconds. If you have (1000 * 60 * 60 * 24 * 365.5) 365.5 days worth of milliseconds it's impossible to know if that number of milliseconds spans an entire year and into the next, if it's just short of a year, or if it spans across three years. Same with 30.5 days worth of milliseconds, could span into a second month, could be less than a month, could span across three months.
Assuming you can start with 2 dates and not a single TimeSpan, then you can get the difference in years like this...
The DateTime.AddYears() function has already solved the majority of issues you may encounter with leap years etc. So for a difference in years, start with the earliest of the two dates and repeatedly add 1 year using .AddYears(1) and increment a counter till you have a date which exceeds the later date of the two and the difference in years will be the value of the counter -1.
If you think the 2 dates may be thousands of years apart, you could adapt this logic to repeatedly +100 years, when the later date is exceeded, repeatedly -10 years, when you go below the higher date, finally +1 again till the higher date is exceeded. If you + and - from the counter the number of years you are adding and taking away, you'll end up with counter -1 being the number of whole years difference again.
public int AgeInYears(DateTime date1, DateTime date2)
{
int age = 0;
DateTime low;
DateTime high;
DateTime test;
if(date1 < date2)
{
low = date1;
high = date2;
}
else
{
low = date2;
high = date1;
}
test = low;
while(test < high)
{
test = test.AddYears(100);
age += 100;
}
while (test > high)
{
test = test.AddYears(-10);
age -= 10;
}
while(test <= high)
{
test = test.AddYears(1);
age++;
}
return age - 1;
}

Get Hours and Minutes from Datetime

Out Time :
2013-03-08 15:00:00.000
In Time :
2013-03-08 11:21:03.290
I need to get Hours and Minutes separately for same date from above, when (Out Time - In Time).
How can I do that ?
I think you probably just want:
TimeSpan difference = outTime - inTime;
int hours = (int) difference.TotalHours;
int minutes = difference.Minutes;
Note that Minutes will give you "just the minutes (never more than 59)" whereas TotalHours (truncated towards zero) will give you "the total number of hours" which might be more than 23 if the times are more than a day apart.
You should also consider what you want to do if the values are negative - either consider it, or explicitly rule it out by validating against it.
The Subtract method on the DateTime class will allow you subtract that date from the other date.
It will give you a TimeSpan which will be the difference.
I'll leave it to you to work out the actual code.
http://msdn.microsoft.com/en-GB/library/8ysw4sby.aspx
You can use Hours property and Minutes
link : http://msdn.microsoft.com/en-us/library/system.datetime.hour.aspx

Categories