Getting totalminutes without decimals - c#

I have this code:
timeSpent = endTime - startTime;
msgArea.Items.Add(timeSpent.Hours + " Hours");
I want it to return minutes as integer, insted of decimals.
I tried Convert.ToInt32(...), but not allowed.
Right now it will return 0.0023304343 as an example, if it is less than 1 min. I want it to just say 0 minutes
Thanks in advance

You just need to cast it if you're not interested in the decimal places:
decimal d = 0.0023304343m;
int i = (int)d;
But i assume that you want to format your TimeSpan as this:
string output = string.Format("{0} Days, {1} Hours and {2} Minutes"
, (int)timeSpent.TotalDays
, timeSpent.Hours
, timeSpent.Minutes);
As you can see there are Total... properties which return the total amount of the unit as double and Hours/ Minutes etc. properties which return an integer. The difference is:
TotalHours for example can be 36.1234
Hours is always an int, the part of the day, Minutes the part of the Hour etc
It's worth noting that since .NET 4 you can also use ToString with a format string since TimeSpan implements IFormattable. I just find it difficult to remember how to escape it properly:
string output = timeSpent.ToString(#"hh\:mm"); // for example
output = timeSpent.ToString("d' Days, 'h' Hours, 'm' Minutes.'"); // your example

You can use Math.Floor:
var hours = (int)Math.Floor(timeSpent.Hours);

Related

Sum times over 24:00 in C#

I want to collect a few hours, but if sum is over 24:00 I take as like it: 1.01:20
How can it in c#:
23:00 + 02:00 = 25:00 ?
Best regards
What has this question to do with Mysql at all? You are asking about the sum of multiple C# TimeSpan, aren't you? Then TotalHours might give you the answer:
TimeSpan ts = TimeSpan.FromHours(23);
ts = ts + TimeSpan.FromHours(2);
int hours = (int) ts.TotalHours;
If you want the sum as formatted string "25:00", use this approach:
string hourMinute = $"{((int)ts.TotalHours).ToString("D2")}:{ts.Minutes.ToString("D2")}";
The ToString("D2") ensures that you always have at least two digits for the hours and minutes, with a leading zero if necessary. Read: Standard numeric format strings

If condition not working as expected c#

This is now bugging me , i have tried to fix it for the past hour but still no luck!
I hope some one could spot what i'm doing wrong . here is my code:
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = '2017-03-07 12:47:58.967';
double totalDays = (lastAction - today).TotalDays;
var days = Math.Round(totalDays);
if(days > maxDays)
{
//never hits this even though days is greater than max days ..i'm so confused
}
what am i doing wrong?
Duplicate problem as here:
C# Number of days between two dates problem
Timespan.TotalDays can be negative. So in your case it is almost guaranteed that lastAction - today will be a negative number, and so will always be less than 30.
If you only care about the absolute value of days, use Math.Abs otherwise re-arrange so that you are subtracting lastAction from today (today - lastAction).
Note that due to rounding, your condition will still not be triggered if there is less than 1 day difference.
Is it possible you are subtracting a larger value (today) from a small value (lastaction) which should result in a negative number making days negative?
That and you do need to do an explicit parse on the string to make it a date:
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58
.967");
Couple of things.
First you cant convert a string to DateTime like that. You should do something like this instead. DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
Second, Just as #MikeS said, you are subtracting the lastAction from Today, which is resulting in a negative number (in this case its like -173). You should flip that statement. double totalDays = ( today - lastAction).TotalDays;
Your whole section should look something like this.
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
double totalDays = ( today - lastAction).TotalDays;
var days = Math.Round(totalDays);
if (days > maxDays)
{
// now this is hit
}
Thanks for the help. I did something stupid .. I had
double totalDays = (lastAction - today).TotalDays; // returns -176
changed my code to:
double totalDays = (today - lastAction).TotalDays; //returns 176
Your first problem:
You didn't parse the string to DateTime.
DateTime lastAction = Convert.ToDateTime("2017-03-07 12:47:58.967");
Your second problem:
You were receiving a negative value, and checking if it's bigger.
var days = (Math.Round(totalDays)) * (-1);
Like this, it should work.

C# time subtraction Issue

I have been facing issue on time subtraction in C#.
For example I start timer on 4/5/2017 11:56:27 PM and end the timer in 5/5/2017 12:10:27 AM when I subtract this it shows me result 23 hours.
I want that it show exact time like 14 minutes. I am sharing my code as well.
double rate1 = Convert.ToDouble(rate.Text);
double value = rate1 / 3600;
DateTime dt = DateTime.Parse(text3.Text);
DateTime edt = DateTime.Parse(text5.Text);
var res = dt.Subtract(edt).ToString().Replace('-', ' ');
DateTime tt = Convert.ToDateTime(res);
DateTime dt1 = DateTime.Parse(text4.Text);
DateTime edt1 = DateTime.Parse(text6.Text);
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');
double sec = TimeSpan.Parse(res).TotalSeconds;
double sec1 = TimeSpan.Parse(res1).TotalSeconds;
text7.Text = res.ToString();
text8.Text = res1.ToString();
It seems like you're showing a lot of code that's difficult to reproduce for us, and the variable names are not the clearest. I'm assuming dt stands for "datetime", and edt stands for "end datetime". If that's correct, then you're subtracting the end date from the start date instead of the other way around (you should subtract the smaller from the larger).
So, here's how to get the difference between start and end (I'm using Hindi culture info for this):
var dateFormatCulture = new CultureInfo("hi-IN");
var startDate = DateTime.Parse("4/5/2017 11:56:27 PM", dateFormatCulture);
var endDate = DateTime.Parse("5/5/2017 12:10:27 AM", dateFormatCulture);
var difference = endDate.Subtract(startDate);
You say you want "the exact time like 14 minutes". I'm not sure if that means you don't want to show the rest of the values, but here are a few ways you can display it.
Console.WriteLine($"General short string format: {difference:g}");
Console.WriteLine(
"Custom string format: {0} days, {1} hours, {2} minutes, {3} seconds",
difference.Days, difference.Hours, difference.Minutes, difference.Seconds);
Console.WriteLine("In terms of minutes, the total minutes difference is: {0}",
difference.TotalMinutes);
Notice that there's a difference between the second an third example in the methods being called to show the minutes . Minutes will display just the minutes portion of the difference. TotalMinutes will display the entire difference in terms of minutes. In your case they are the same, but if the difference was 1 hour and 14 minutes, Minutes would still be 14, but TotalMinutes would be 74.
The output looks like:
It looks like you might have a copy/paste error. In this line, did you mean to reference dt1 rather than dt?
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');

How to get Difference hours Between two date

I want get diffrences Day,Hour and Day between two days.
I use belowe Code :
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
When I want get Hours its return mines (-11 e.t).
How can I get positive Diffrence Hour ?
anyone can you help me?
I want get Last Dat and show its by string how days afterd now.
You're subtracting component-wise (i.e. "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of lastDate, or the same for minute-of-hour - you get a negative value, exactly as you've seen.
Instead, subtract one DateTime from another to get a TimeSpan and use that single TimeSpan for all the components:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
TimeSpan difference = DateTime.Now - lastDate;
int days = difference.Days;
int hours = difference.Hours;
int minutes = difference.Minutes;
That will still be negative if lastDate is after DateTime.Now, of course.
Note that this will give you a result which is meaningful if you display all three components. For example, it might give you "2 days, 3 hours and 10 minutes". If instead you want to represent the same TimeSpan as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use TotalDays, TotalHours and TotalMinutes.
If you always want a positive TimeSpan - the equivalent of Math.Abs but for TimeSpan you can just use TimeSpan.Duration():
TimeSpan difference = (DateTime.Now - lastDate).Duration();

How to Round to the Nearest 0.5?

in my application
Ex 1: Start time 12.30
(-)End time 16.00 here i get the value as 3.7 but i need to show this 3.7 as 3.5 in my application
Ex 2: Start time 12.00
(-)End time 16.00 here i get the value as 4.0 here there is no need to alter the value
(1.7,2.7,3.7,4.7,.... etc ) as to be represented as(1.5,2.5,3.5,4.5,.. etc )
so how to write an function for this where if the vale contains(1.7,2.7) i should change to 1.5,2.5
or if it contains 1.0,2.0 then there is no need to replace any value?
This extension method ought to do the job:
public decimal RoundToNearestHalf(this decimal value)
{
return Math.Round(value * 2) / 2;
}
var num1 = (3.7).RoundToNearestHalf(); // 3.5
var num1 = (4.0).RoundToNearestHalf(); // 4.0
I've used the decimal type in the code because it seems you want to maintain base 10 precision. If you don't, then float/double would do just as well, of course.
Use the DateTime type. Subtracting DateTime types returns a TimeSpan. Use TimeSpan.TotalHours to get your result. E.g.:-
var x = DateTime.Parse("12:30");
var y = DateTime.Parse("16:00");
Console.WriteLine((y - x).TotalHours);
Use DateTime type to work with time. Example:
string time1 = "12:30";
string time2 = "16:00";
TimeSpan diff = DateTime.Parse(time2)-DateTime.Parse(time2);
string diffString = diff.ToString("hh:mm"); // will be 03:30
Multiply hours with 60 and add minutes. You'll get total number of minutes.
12hours and 30 minutes = 720 + 30 = 750 minutes.
16 hours = 960 minutes.
Subtract the first value from the other and divide it by 60
(960 - 750) / 60 = 210 / 60 = 3.5
You should use TimeSpan and round it off:
TimeSpan startTime = new TimeSpan(12, 30, 0);
TimeSpan endTime = new TimeSpan(16, 0, 0);
TimeSpan span = endTime - startTime;
double totalHours = span.TotalHours;
double roundedToHalf = Math.Round(totalHours * 2) / 2;
Console.WriteLine(roundedToHalf);
UPDATE:
If the start and end time are from different dates, you should use DateTime for startTime and endTime.
If the values in your question represent times you can't do decimal arithmetic with them and expect time values as results.
You need to manipulate the values as times
I don't know C#, but it must have some time functions.
Have the times as DateTime then use Timspan to find the difference between the two times?
Times are not integers or floats. You can't work with them as if they are - you wouldn't try to do integer math using the String class, would you?
DateTime and TimeSpan are you friends for this kind of data manipulation.
You can use the C# Floor and Ceil method of the Math Class. Read more about it in the below URLs:
http://msdn.microsoft.com/en-us/library/system.math.ceiling(VS.71).aspx
http://dotnetperls.com/math-floor
string i = "2.0";
if (i == "2.3" || i == "3.3" || i == "4.3")
{
string strReplace = i.Replace(".3", ".5");
}
else
{
string strReplace = i;
}

Categories

Resources