Sum times over 24:00 in C# - 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

Related

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.

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();

Getting totalminutes without decimals

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);

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

I want to show in a TextBox only hour and minutes
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
how to show only hours and minutes "hh.mm"
You need to convert your data to TimeSpan and then use format:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(#"hh\:mm"));
In your case:
var test = dataRow.Field<TimeSpan>("fstart").ToString(#"hh\:mm"));
Remember to escape the colon :
You may see: Custom TimeSpan Format Strings
There is no need to convert from hh.mm.ss to hh.mm. TimeSpan is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the TimeSpan into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case hh.mm.ss.
string formatted = timespan.ToString(#"hh\.mm");
Note: This overload of ToString exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.
The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format(#"{0:hh\.mm}", timespan); // ==> 00:20:34
However, you can construct the string like this
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
or starting with VS2015 / C# 6.0, using string interpolation:
string formatted = $#"{timespan:hh\:mm}";
You can use TimeSpan methods:
ToString("hh':'mm")
// or
ToString(#"hh\:mm")
Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
I know this is a very old question. If anyone wants to show single-digit hours when your hours are a single digit then you can use
var hoursWithMinutes = TimeSpan.FromHours(hours).ToString(#"h\:mm")
This way, when your hours are double-digit I mean greater than 9 then it will be showing 10:00 something like that.
The previous solutions don't run if hours>24, try this solution if you have time in minutes very big
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;
You can achieve this by:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(#"hh\:mm")

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