Subtract TimeSpan bigger than 24H - c#

I need to compare two TimeSpan values bigger than 24 hours.
For that I use the following code
string startTime = textBox1.Text;
string endTime = textBox21.Text;
TimeSpan startTimet = new TimeSpan(int.Parse(startTime.Split(':')[0]), // hours
int.Parse(startTime.Split(':')[1]), // minutes
0);
TimeSpan endTimet = new TimeSpan(int.Parse(endTime.Split(':')[0]), // hours
int.Parse(endTime.Split(':')[1]), // minutes
0);
TimeSpan duration = endTimet.Subtract(startTimet);
label29.Text = duration.ToString();
If the values aren't bigger than 24H it's all ok, but if I have a value bigger than 24h the TimeSpan will appear like DD.HH.MM.SS.
For example:
endTimet = 32:15
startTimet = 02:00
duration = 1.06:15:00
And what I really need is the normal format like HH:MM, assuming the hours are greater than 24, getting the expected 30:15
Can anyone help me here?
Regards

Perhaps with this workaround:
TimeSpan duration = TimeSpan.FromHours(30);
string result = string.Format("{0}:{1}"
, duration.TotalHours
, duration.Minutes); // 30:00

Noda Time to the rescue!
string s1 = "123:45";
string s2 = "234:56";
DurationPattern p = DurationPattern.CreateWithInvariantCulture("H:mm");
Duration d1 = p.Parse(s1).Value;
Duration d2 = p.Parse(s2).Value;
Duration diff = d2 - d1;
string result = p.Format(diff); // "111:11"

Related

Get time until next occurrence of 6pm?

I've got a thread that is only set to run within a certain period otherwise it's put on delay. From the time of running that threads of a certain Boolean value if true, then it should be delayed by X amount of time from current time to 18:00. Is there a quick way doing this in c#?
DateTime today = DateTime.Now;
DateTime tomorrow = today.Add(new TimeSpan(1,0,0,0));
DateTime tomorrowAtSix = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 18,0,0 );
TimeSpan diff = tomorrowAtSix.Subtract(DateTime.Now);
double hoursFromNow = 0d;
double minutesFromNow = 0d;
if(diff.TotalHours > 24d) // next 6pm is tomorrow
{
hoursFromNow = diff.TotalHours - 24d;
minutesFromNow = diff.TotalMinutes - (24d * 60d);
}
else // next 6pm is today
{
hoursFromNow = diff.TotalHours;
minutesFromNow = diff.TotalMinutes;
}
You can subtract DateTime objects which will return a TimeSpan
TimeSpan ts = DateTime.Now - new DateTime(2017, 1, 1);

Remove Minutes from a Timespan duration

I know this has been asked before but i couldn't figure out how to get the answers given working for my particular example. This is a WPF application written in C# and i'm trying to remove a number of minutes from a timespan.
So far i've got the application to figure out the duration by removing a Start Time from a Finish Time, but what i'm trying to do now is remove the number of minutes the user has entered into the form.
Here's the code so far
private void testcal_Click(object sender, EventArgs e)
{
string startTime = teststart.Text;
string finishTime = testfinish.Text;
// Trying to deduct this lunchTime var from the duration TimeSpan
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime));
testlabel.Text = duration.ToString(#"hh\:mm");
}
Edit - Updated to include private void
Are you asking how to subtract minutes from a TimeSpan?
If so try something like
TimeSpan ts = new TimeSpan().Subtract(TimeSpan.FromMinutes(30));
With user input it would be.
string startTime = teststart.Text;
string finishTime = testfinish.Text;
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime)).
Subtract(TimeSpan.FromMinutes(Int32.Parse(lunchtime)));
DateTime selectedDate = DateTime.Parse("10/09/2021");
DateTime now = DateTime.Now;
TimeSpan subtract = now - selectedDate;
subtract -= new TimeSpan(7, 0, 0, 0);

How to find total from a concatenated value?

I have two concatenated values such as
string BreakOut = "10:15 Mintes";
string BreakIn = "10:30 Minutes";
I want result as
Total=15 Minutes
It is a time difference calculation. But values are not in a time format it is in a string format. How can I do this. Please suggest a way. I tried like
TimeSpan span=Convert.ToDateTime(BreakOut ).Subtract(Convert.ToDateTime(BreakIn ));
There is no point to parse them to DateTime since they are time interval. TimeSpan would be better choice since it is exactly what this for.
If Mintes is typo and your values are always the same standard format, you can easily split them with white space and then parse to TimeSpan.
For example;
var BreakOut= "10:15 Minutes";
var BreakIn = "10:30 Minutes";
BreakOut = BreakOut.Split(new string[]{" "},
StringSplitOptions.RemoveEmptyEntries)[0];
BreakIn = BreakIn.Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries)[0];
var ts1 = TimeSpan.Parse(BreakOut, CultureInfo.InvariantCulture);
var ts2 = TimeSpan.Parse(BreakIn, CultureInfo.InvariantCulture);
var difference = ts2 - ts1;
Console.WriteLine("{0} minutes", difference.TotalMinutes); // 15 Minutes
Here a demonstration.
if your values always refers to the same day,
you can use something like that :
string BreakOut="10:15" ;
string BreakIn ="10:30";
double res =DiffInMinutes(BreakIn, BreakOut);
//Total=15 Minutes
public static double DiffInMinutes(string _BreakIn, string _BreakOut)
{
double diff = 0;
string[] BreakIn = _BreakIn.Split(':');
string[] BreakOut = _BreakOut.Split(':');
//timeSpan instanciated with Hours/minutes/seconds
TimeSpan TimeElapsed = new TimeSpan(int.Parse(BreakOut[0]) - int.Parse(BreakIn[0]), int.Parse(BreakOut[1]) - int.Parse(BreakIn[1]), 0);
diff = TimeElapsed.TotalMinutes;
return diff;
}
I downvoted your question, but maybe you really dont know that there is TimeSpan.Parse
string breakOut = "10:15 Minutes";
string breakIn = "10:30 Minutes";
string cleanBreakIn = breakIn.Split(' ')[0];
string cleanBreakOut = breakOut.Split(' ')[0];
TimeSpan total = TimeSpan.Parse(cleanBreakIn) - TimeSpan.Parse(cleanBreakOut);

How do I convert a string of numbers to 24 time

How do I convert a string of numbers to 24 time
string example would be something like "0800" or "1200" or "2400"
I'd like this to be parsed to time data type (but without date) so that I can compare 2 times against each other. I parsed them as int numbers, but then it trimmed left zero's on numbers like "0800"
var ts = TimeSpan.ParseExact("1500", "hhmm",null);
You can compare them, for ex
var ts1 = TimeSpan.ParseExact("1500", "hhmm", null);
var ts2 = TimeSpan.ParseExact("2000", "hhmm", null);
var mins = ts2.Subtract(ts1).TotalMinutes;
If you want the result as DateTime object, take a look at the DateTime.ParseExact method:
DateTime.ParseExact(dateString, "HHmm", CultureInfo.InvariantCulture);
Since you don't want the date portion, TimeSpan is your best bet.
CODE:
var time1 = "0800";
var time2 = "1200";
var time3 = "2359"; // 2400 is not a valid time
var ts1 = TimeSpan.ParseExact(time1, "hhmm", CultureInfo.InvariantCulture);
var ts2 = TimeSpan.ParseExact(time2, "hhmm", CultureInfo.InvariantCulture);
var ts3 = TimeSpan.ParseExact(time3, "hhmm", CultureInfo.InvariantCulture);
Console.WriteLine(ts1);
Console.WriteLine(ts2);
Console.WriteLine(ts3);
// Calculating time difference.
var tsDiff = ts1.Subtract(ts2);
Console.WriteLine(tsDiff);
OUTPUT:
08:00:00
12:00:00
23:59:00
-04:00:00

Calculate how many hours until 8 AM

I know how to calculate the difference between two dates, but how do I calculate the time between a given date and the next 8 AM?
var now = DateTime.Now;
var tomorrow8am = now.AddDays(1).Date.AddHours(8);
double totalHours = ( tomorrow8am - now).TotalHours;
var now = DateTime.Now;
double diffHours = 24 - (now - now.Date).TotalHours + 8;
How about something like this
var now = DateTime.Now();
var target = DateTime.Today.AddDays(1).AddHours(8);
var result = (target - now).Hour;
Works well before 8am the same day.
DateTime now = DateTime.Now;
DateTime next8am =now.Date.AddHours(8);
if(now.TimeOfDay>TimeSpan.FromHours(8))
next8am.AddDays(1);
return next8am.Subtract(now).TotalHours

Categories