Compare to dates [duplicate] - c#

I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values.
For that, I create a timespan variable to store the difference of the 2 date values.
TimeSpan? variable = datevalue1 - datevalue2;
Now i need to show the difference which is stored in the Timespan variable in terms of number of hours.
I referred to TimeSpan.TotalHours but couldn't apply the same for some reason.
How do I do that?
I am using C# on a MVC project. I simple need to show the difference value in hours?
EDIT:
Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours;

you may also want to look at
var hours = (datevalue1 - datevalue2).TotalHours;

I think you're confused because you haven't declared a TimeSpan you've declared a TimeSpan? which is a nullable TimeSpan. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours.

In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object.
Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
Result:
Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0

Is there a reason you're using Nullable?
If you want to use Nullable then you can write variable.Value.TotalHours.
Or you can just write: (datevalue1 - datevalue2).TotalHours.

Here is another example of subtracting two dates in C# ...
if ( DateTime.Now.Subtract(Convert.ToDateTime(objDateValueFromDatabase.CreatedOn)).TotalHours > 24 )
{
...
}

a more precise way for employee paid hours or other precision requirement::
decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
var span = (stopTimestamp - startTimestamp).Value;
decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
return Math.Round(total, PRECISION_CONSTANT);
}
https://dotnetfiddle.net/tVIoVJ

var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)
can also add difference between the dates if we compare two different dates
new TimeSpan(24 * days, 0, 0)

WOW, I gotta say: keep it simple:
MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));
Result: True
and:
MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));
Result: 10.00:00:00
The DateTime object has all the builtin logic to handle the Boolean result.

Related

Minute give wrong values on substract

I want to subtract minutes and get the difference. below is my code
double diff = currBlock.EndTime.Subtract(currBlock.StartTime).TotalMinutes;
In given code (currBlock.StartTime = 23:30:00) and (currBlock.EndTime= 00:20:00)
here starttime is time of today i.e.(09/26/2016 23:30:00), night time which will be consider as 11:30 PM and endtime is time of tomorrow i.e.(09/27/2016 00:20:00), morning time which will be consider as 12:20 Am. In my code i am getting values in minus which is -1390 and it is incorrect. So please help me to solve this.
Here i have attach image of data for further reference.
please explain me properly, how do i use it? it is just a time block for different shift so there is no date include in it
There is a date included in it. You're telling us that EndTime is something like 09/27/2016 00:20:00, while StartTime is something like 09/26/2016 23:30:00. The problem is that that knowledge is in your head and not in your code. If you subtract the values as TimeSpans, then you're literally saying: what is 30 minutes minus 23 hours and 30 minutes. The answer, of course is -23 hours. To get the real difference, you must include the dates, which means utilizing a DateTime or DateTimeOffset type for both StartTime and EndTime, so you can encode that whole date and time. Then, when you do the subtraction, it will return the right value.
Below Code works for me. Thanks friends for your support and help.
string strCurrDate = (DateTime.Now.Date + currBlock.EndTime).ToString();
DateTime dtYourDate = DateTime.Parse((DateTime.Now.AddDays(-1).Date + currBlock.StartTime).ToString());
string strYourDate = dtYourDate.ToShortDateString() + " " + dtYourDate.ToLongTimeString();
string strTotalMinsElapsed = TotalMinutesElapsed(dtYourDate).ToString();
private long TotalMinutesElapsed(DateTime dtYourDate)
{
long lTotalMinutesElapsed = 0;
//Find Current Date and Time
DateTime dtCurrent = DateTime.Now;
//Find Time Difference details between current date and your given date
TimeSpan tsDiff = dtCurrent.Subtract(dtYourDate);
//Add Total Minutes for Days difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Days * (24 * 60);
//Add Total Minutes for Hour difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Hours * 60;
//Add Minutes
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Minutes;
return lTotalMinutesElapsed;
}

Difference between two string time and now

I have a string like that 03223311 (hhmmssff). I'm going to compare it with DateTime.Now and see if the difference between these to values is lower than 200 miliseconds.
xdate="03223311";
if(Math.Abs(Convert.ToInt32(xdate) - Convert.ToInt32(DateTime.Now.ToString("hhmmssff")))<200)
I tried to run the line above in a timer with interval of 1 but I can not reach to that condition even if I change xdate to current time... . Do you know how to solve the problem or even a better approach?
string input = "03223311";
var diff = DateTime.Now.TimeOfDay.Subtract(
TimeSpan.ParseExact(input, "hhmmssff", null)
).TotalMinutes; //or any other value like TotalMilliseconds
I would first convert the string into a DateTime so that you can compare apples to apples and utilized the features of the DateTime object. Once you have two DateTime objects, you can subtract them to get a TimeSpan. TimeSpan will have a TotalMilliseconds property that you can compare to your 200 constant.
var xdateValue = DateTime.ParseExact(xdate, "hhmmssff", CultureInfo.InvariantCulture);
var difference = DateTime.Now - xdateValue;
if (difference.TotalMilliseconds < 200) ...
if (((DatetTime.Now - DateTime.ParseExact("03223311 ", "hhmmssff", CultureInfo.InvariantCulture))).Milliseconds > 200)
{
}

How to find difference for two time values in string?

I am working on a new project in c#, i have no experience with date and time.
Here i need to find the difference between two time values which is in string format
string pointavalue = comboBox1.Text + ":" + comboBox2.Text + ":" + comboBox5.Text;
string pointbvalue = comboBox3.Text + ":" + comboBox4.Text + ":" + comboBox6.Text;
string pointcvalue = comboBox7.Text + ":" + comboBox8.Text + ":" + comboBox9.Text;
DateTime pointa = DateTime.Parse(pointavalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointb = DateTime.Parse(pointbvalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointc = DateTime.Parse(pointcvalue, System.Globalization.CultureInfo.CurrentCulture);
string time1 = pointa.ToString("HH:mm:ss");
string time2 = pointb.ToString("HH:mm:ss");
string time3 = pointc.ToString("HH:mm:ss");
There is three Values pointavalue, pointbvalue. pointcvalue.
They are combined string values of comboboxes.
Now how do i subtract pointbvalues from pointavalues?
I know they are in string format so operations cannot be performed.
the code you are looking is not mine, someone helped me but its working as a expected.
I am learning C# so bear with me.
ok i think figure out something, but still i can't solve it.
Here is my recent work with the code
DateTime inputa = DateTime.Parse(label21.Text, System.Globalization.CultureInfo.CurrentCulture);
DateTime inputb = DateTime.Parse(label23.Text, System.Globalization.CultureInfo.CurrentCulture);
if (pointa < pointb)
{
TimeSpan diff1 = pointb.Subtract(pointa);
DateTime d1=Convert.ToDateTime(diff1);
if (d1 < inputa)
{
label34.Text = "fail";
}
else
{
label34.Text = "pass";
}
Here i want to check the condition of the time diff1 and inputa, that's it that's all i need to finish this project.
The reason why you can't solve this problem is that you are trying to compare two different data types, Timespan and Datetime are not same
Either convert all your string to "Timespan" (That is better option).
Datetime will give you the present date, but it seems you don't need that.
Last but not least learn some basics before you ask these questions.
One more simple example:
void Main()
{
DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
TimeSpan difference = yesterday - now;
Console.WriteLine (difference.GetType().Name);
Console.WriteLine (difference.TotalSeconds); // expecting -86400
}
running this will print
TimeSpan
-86400
Take a look at the DateTime.Substract method:
TimeSpan abdiff = pointb.Substract(pointa);
TimeSpan bcdiff = pointc.Substract(pointb);
Alternatively, you can use the - operator, you get back a Timespan which contains the differences:
TimeSpan abdiff = pointb - pointa;
TimeSpan bcdiff = pointc - pointb;
Assuming that your combo boxes contain the hour, minute, and second then you could do the following.
TimeSpan pointa = new TimeSpan(int.Parse(comboBox1.Text), int.Parse(comboBox2.Text), int.Parse(comboBox5.Text));
TimeSpan pointb = new TimeSpan(int.Parse(comboBox3.Text), int.Parse(comboBox4.Text), int.Parse(comboBox6.Text));
TimeSpan pointc = new TimeSpan(int.Parse(comboBox7.Text), int.Parse(comboBox8.Text), int.Parse(comboBox9.Text));
TimeSpan aTob = pointa > pointb
? pointa - pointb
: (pointa + TimeSpan.FromDays(1)) - pointb;
Basically this assumes that your combo boxes only have valid hour (0-23), minute (0-59), and second (0-59) values. Then you just need to determine if your times are on the same day or not. If you assume that pointa is latter than pointb then checking if it is greater than pointb means you can do a straight subtraction. If not then it must be the time for the next day and you just add 1 day to it before subtracting pointb.
This is based on your assertion that 01:00 - 23:00 should be 2 hours and not -22. Thought it would be best if there where a date included so you would know for sure if the times are on the same day or the next day or from completely different years.

c# reproduce datetime from ticks

I have a datetime field like
{01/01/0001 00:01:02}
Millisecond = 30 and the Ticks for the above datetime field is
6203000000
The ticks save in the database as an int value which is 62030. I need to reproduce the above date time using the value in the database (62030). So I tried the following.
var data = 62030;
winTime = new DateTime().AddTicks(Convert.ToInt64(data.ToString().PadRight(10, '0')));
var b = winTime.Ticks;
var b = 6203000000. But it returns minute as 10 instead 01, second as 20 instead of 02 and Millisecond as 300 instead of 030.
Can anyone see what I'm doing wrong?
It seems to me that your "ticks 62030" is actually "milliseconds 62030" in which case it's very simple - you just need to multiply by "the number of ticks per millisecond" which is 10,000. You don't need to use DateTime for this at all:
// Note that if you want any significant length of time, you'd expect to get
// the data as a long, not an int
int data = 62030; // Milliseconds
long ticks = data * 10000L;
... and you certainly don't need string conversions. Converting to a string, padding, and then converting back again is a very tortuous and error-prone way of performing multiplication.
Or if you do need a DateTime:
int data = 62030; // Milliseconds
long dateTime = new DateTime(data * 10000L);
I strongly suspect that any DateTime value that early should actually be treated as a TimeSpan though - what's this really meant to represent? If so, it's even easier:
TimeSpan ts = TimeSpan.FromMilliseconds(data);
Date and time concepts are very easy to mix up, and you end up with some very subtle bugs. Personally I'd recommend using my Noda Time project which separates them more than .NET does, but even if you don't use the library it's worth looking at the list of concepts so you can think about them appropriately within .NET too.
Why not just use the DateTime constructor that accepts an Int64 representing ticks, such that:
var dateTimeFromTicks = new DateTime(ticks);
static void Main(string[] args)
{
/* read datetime now */
DateTime dt = new DateTime();
dt = DateTime.Now;
/* datetime convert to tick */
long TickeringTick = dt.Ticks;
Console.WriteLine("Date time now -> " + dt.ToString("yyyy.MM.dd HH:mm:ss.fffffff"));
Console.WriteLine("Converted to Ticks = " + TickeringTick.ToString());
/* convert tick to datetime */
long myTicks = TickeringTick;
DateTime dt2 = new DateTime(myTicks);
Console.WriteLine("Date from ticks :" + dt.ToString("yyyy.MM.dd HH:mm:ss.fffffff"));
Console.ReadLine();
}

C#: how do I subtract two dates?

Here's my code:
DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = datenow - date1
On the last line I am getting this error:
Error 1 Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'
How do I subtract two dates?
Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().
TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`
This will make your current code work.
If on the other hand you want to subtract, let's say, one year from your date, you can use:
DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year
As already mentioned, date - date gives you a TimeSpan, not a DateTime. If you want a DateTime, use AddDays(-1) as in:
DateTime subtractedDate = date1.AddDays(-1);
The result of a date comparison is a TimeSpan, not a DateTime value.
You want to do this:
TimeSpan result = datenow - date1;
.Subtract has two overloads. One accepts a DateTime and returns a TimeSpan, the other accepts a TimeSpan and returns a DateTime.
In other words, if you subtract a date from a date, you get the timespan difference. Otherwise, if you subtract a timespan from a date, you get a new date.
Can you clarify what you are trying calculate? The difference between any two dates in C# or real life is a time span. If you are trying to calculate age then what you want is the timespan since their birth. Change Date2 to to
Timespan age = datenow - date1;
You are correctly subtracting two dates in your code. What's going on is that you expect the difference between the two dates to be another date, and that's not the case.
As other posters have noticed, you get a TimeSpan. From your variable names I get the sense you're trying to find out someone's age.
Age is not a date, it's a duration. Read up on the TimeSpan object and you will find that it correctly expresses the idea you are looking for.
I'm not 0029-01-01 years old, I'm 29 years old. (Today is not my birthday, but assume it is for easy math.)
If you're trying to show someone's age in a control and that control wants a DateTime you are probably using the wrong control to do it.
Try using ticks...?
DateTime date1 = new DateTime(1986, 3, 16, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = new DateTime(datenow.Subtract(date1).Ticks);
You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.
DateTime now = DateTime.Now;
// Get the date 7 days ago
DateTime sevenDaysAgo = now.AddDays(-7);
// Bulk: Get the date 7 days and two hours ago
DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));
Use this code:
DateTime? Startdate = cStartDate.GetValue<DateTime>().Date;
DateTime? Enddate = cEndDate.GetValue<DateTime>().Date;
TimeSpan diff = Enddate.GetValue<DateTime>()- Startdate.GetValue<DateTime>() ;
txtDayNo.Text = diff.Days.GetValue<string>();
TimeSpan Example:
private void Form1_Load(object sender, EventArgs e)
{
DateTime startdatetime = new DateTime(2001, 1, 2, 14, 30, 0);
DateTime enddatetime = DateTime.Now;
TimeSpan difference = enddatetime.Subtract(startdatetime);
string sdifference = "TotalDays:" + difference.TotalDays + Environment.NewLine;
sdifference += "TotalHours:" + difference.TotalHours + Environment.NewLine;
sdifference += "TotalMilliseconds:" + difference.TotalMilliseconds + Environment.NewLine;
sdifference += "TotalMinutes:" + difference.TotalMinutes + Environment.NewLine;
sdifference += "TotalSeconds:" + difference.TotalSeconds + Environment.NewLine;
sdifference += "Ticks:" + difference.Ticks + Environment.NewLine;
sdifference += "Total:" + difference.Days + " days, " + difference.Hours + " hours, " + difference.Minutes + " minutes, " + difference.Seconds + " seconds and " + difference.Milliseconds + " milliseconds.";
TextBox TextBox1 = new TextBox();
TextBox1.Multiline = true;
TextBox1.Dock = DockStyle.Fill;
TextBox1.Text = sdifference;
this.Controls.Add(TextBox1);
}
Not exactly an answer to your question, but I prefer using var instead of annotating the variables with types. var IMO makes code look much cleaner than otherwise.
Here's your code snippet with vars:
var date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
var datenow = DateTime.Now;
var date2 = datenow - date1;
EDIT:
For the C# developers with the var-is-bad mindset:
[ Original Post Here ]
I use var extensively. There has been
criticism that this diminishes the
readability of the code, but no
argument to support that claim.
Admittedly, it may mean that it's not
clear what type we are dealing with.
So what? This is actually the point of
a decoupled design. When dealing with
interfaces, you are emphatically not
interested in the type a variable has.
var takes this much further, true, but
I think that the argument remains the
same from a readability point of view:
The programmer shouldn't actually be
interested in the type of the variable
but rather in what a variable does.
This is why Microsoft also calls type
inference “duck typing.”
So, what does a variable do when I
declare it using var? Easy, it does
whatever IntelliSense tells me it
does. Any reasoning about C# that
ignores the IDE falls short of
reality. In practice, every C# code is
programmed in an IDE that supports
IntelliSense.
If I am using a var declared variable
and get confused what the variable is
there for, there's something
fundamentally wrong with my code. var
is not the cause, it only makes the
symptoms visible. Don't blame the
messenger.
Now, the C# team has released a coding
guideline stating that var should only
be used to capture the result of a
LINQ statement that creates an
anonymous type (because here, we have
no real alternative to var). Well,
screw that. As long as the C# team
doesn't give me a sound argument for
this guideline, I am going to ignore
it because in my professional and
personal opinion, it's pure baloney.
(Sorry; I've got no link to the
guideline in question.)
Actually, there are some
(superficially) good explanations on
why you shouldn't use var but I still
believe they are largely wrong. Take
the example of “searchabililty”: the
author claims that var makes it hard
to search for places where MyType is
used. Right. So do interfaces.
Actually, why would I want to know
where the class is used? I might be
more interested in where it is
instantiated and this will still be
searchable because somewhere its
constructor has to be invoked (even if
this is done indirectly, the type name
has to be mentioned somewhere). -
Konrad Rudolph

Categories