C# time subtraction Issue - c#

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

Related

Get Random Date with hours and minutes from now until 2 days ago

Hi How Can I get a random date with hours and minutes in a range bewtween now and 2 or 3 days ago. ??
Thanks to all
something like this dates time with minutes
10/23/2018 4:32:00 PM
10/23/2018 5:31:00 PM
10/23/2018 1:32:00 AM
10/22/2018 2:00:00 PM
Here I can get the dates in a range, let say 2 days, but the hour is the same
public static DateTime NextDateTime(int endDatenumbers)
{
DateTime startDate = DateTime.Today;
DateTime endDate = startDate.AddDays(-endDatenumbers);
var newDate = startDate.AddHours(new Random(Convert.ToInt32(DateTime.Now.Ticks / int.MaxValue)).Next(0, (int)(endDate - startDate).TotalHours));
return newDate;
}
You should simplify that to 1 random call.
Get the furthest day which is 3 days ago.
var furthestDate= DateTime.Today.AddDays(-3);
You range is actually 2 days after that date which is (48hrs * 60 min) = 2880 minutes.
So anything from that date and 2880 minutes after is valid.
Simply get 1 random number between 0 an 2880. Finally simply add the minutes to the furthest date.
var randomDate = furthestDate.AddMinutes(YouRandomNumber);
The following logic actually computes the number of minutes between the two days. This is important where your days can potentially cross a daylight savings boundary. Also, I am storing the value "today" as technically (albeit unlikely) it could change between the two calls.
private static DateTime PickRandomMinute(int inPastNDays, Random random)
{
DateTime today = DateTime.Today;
int totalMinutes = (int)(today - today.AddDays(-inPastNDays)).TotalMinutes;
return today.AddDays(-inPastNDays).AddMinutes(random.Next(totalMinutes));
}
Example usage:
Random random = new Random();
Console.WriteLine(PickRandomMinute(2, random)); // 22/10/2018 9:34:00 PM (for example)
Console.WriteLine(PickRandomMinute(2, random)); // 23/10/2018 4:55:00 AM (for example)
You don't want to create a new Random within this method because calls that happen very close together would probably end up with the same seed and therefore return the same time.

Calculation with DateTime and TimeSpan in C#

I need to make a calculation of passed and remaining time of an operation in C#.
I have the start of the operation saved in a string format of HH:MM:SS
I have a default time length of the operation in a string format of HH:MM:SS
Now I would like to calculate:
The remaining time / extra time: For example if the operation is still below the default length, it should display -HH:MM:SS, and if the operation took longer than the default time, it should display +HH:MM:SS
If the operation took longer, I would also like to have a double value of HH,MM in % style. For example: 3hours and 30 minutes should be displayed as 3,5
Both results to be displayed next to each other.
I know I have to translate the string values into DateTime and/or TimeSpan values to do calculations, but currently I have no idea how to calculate since the first operation for example would not give me a negative value, but just get back in time [22:30:00 of yesterday].
Try this..
var start = "17:05:11"; // Pass this as a parameter
var startTime = DateTime.Parse(start);
var defaultDuration = TimeSpan.FromMinutes(2);
TimeSpan operationDuration = startTime - DateTime.Now;
TimeSpan diff = defaultDuration - operationDuration;
if (operationDuration > defaultDuration)
{
Console.Out.WriteLine($"+{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
}
else
{
Console.Out.WriteLine($"-{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
Console.Out.WriteLine($"{diff.Hours},{Math.Round(((double)(diff.Minutes * 100 / 60)),0, MidpointRounding.AwayFromZero)}");//example: 3hours and 30 minutes should be displayed as 3,5
}
At first save the default time as TimeSpan. Then you can take DateTime.Now and save it when the operation starts. Take another DateTime.Now later when it finished. After this point you can calculate the TimeSpan for the current operation. Then you can calculate the difference from these two TimeSpans as another TimeSpan. It can be positive or negativ and with these values you can do whatever you want.
TimeSpan defaultDuration = new TimeSpan(3, 30, 0);
DateTime begin = DateTime.Now;
//Do some work
DateTime end = DateTime.Now;
TimeSpan thisDuration = end - begin;
Console.WriteLine("Default: " + defaultDuration.ToString("hh\\:mm\\:ss"));
Console.WriteLine("This time: " + thisDuration.ToString("hh\\:mm\\:ss"));
Console.Write("Difference: ");
if (thisDuration > defaultDuration)
Console.Write("-");
Console.WriteLine((thisDuration - defaultDuration).ToString("hh\\:mm\\:ss"));

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

Does DateTime.Now always return a 24 hour format by default?

Currently it is evening and couldn't actually test it with morning hours like 7 in the morning.
but a code like this:
DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");
So my question is can I be sure that it is always returning time in format like "07:35" and not "7:35" ?
DateTime.Now returns time without formatting. Format applied in the ToString("HH:mm") method. And yes, this format is 24-hour.
Yes because the documentation says:
The "HH" Custom Format Specifier: The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.
You could test with
DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");
Console.WriteLine(str);
DateTime t = new DateTime(2014,3,27,7,5,0);
str = t.ToString("H:mm");
Console.WriteLine(str);
The HH format return always the hour formatted with two digits adding a leading zero when the hour is less than 10, the H format returns the hours formatted with exactly the digits present in the hour part.
You can create an instance of DateTime with desired date and time values using to test various time setting and formats :
var dt = new DateTime(2014, 1, 1, 7, 35, 0);
string str = dt.ToString("HH:mm");

C# Is it possible to convert DateTime format to integer or float?

I'm having some trouble here.
Did some research on Google but I can't seem to find what I'm looking for.
I'm trying to ask for two inputs (datetimes) in hh:mm format, subtract one for the other then return the result of that value in minutes.
The problem is that I want to return that value as an integer and I can't seem to find the right way to do it.
In C/C++ I wouldn't have this kind of issues...
Anyways, here's a snippet of what I'm talking about.
private int DuraçaoTreino(DateTime dtInicioTreino, DateTime dtFimTreino, int dtDuraçao)
{
Console.WriteLine("Introduza a hora de inicio (hh:mm): ");
dtInicioTreino = Convert.ToDateTime(Console.Read());
Console.WriteLine("Introduza a hora de fim (hh:mm): ");
dtFimTreino = Convert.ToDateTime(Console.Read());
dtDuraçao = (dtFimTreino - dtInicioTreino); // duração da sessão de treino
dtDuraçao = Convert.ToDecimal(Console.Read());
return dtDuraçao;
}
And that's pretty much it... I'm new to C# so if you see anything wrong please be kind.
Thanks in advance.
What you're talking about is a TimeSpan:
DateTime dtBegin = new DateTime(2011,5,1,22,0,0) ; // 10pm 1 May 2011
DateTime dtEnd = new DateTime(2011,5,1,23,0,0) ; // 11pm 1 May 2011
TimeSpan tmElapsed = dtEnd - dtBegin ; // tmElapsed is a TimeSpan with a value of 60 minutes
To return the minutes, do something like:
int elapsedTimeInMinutes = (int) Math.Round( tmElapsed.TotalMinutes , 0 ,MidpointRounding.ToEven ) ;
var timeInMinutes = new DateTime(2011, 12, 25).Subtract(new DateTime(2010, 1, 1)).TotalMinutes;
Instead of creating the DateTime objects using the constructor I used, you can use DateTime.Parse, or better still DateTime.ParseExact to convert the strings to date times. (I know I am only using date parts here but you choose only to use time parts if you wish)
Convert DateTime objects to TimeSpan's, substract and call TimeSpan.TotalMinutes (or smth like that - dont' have VS at hand):
DateTime dt1, dt2;
// Assign some dates, then:
TimeSpan ts = dt2 - dt1;
double minutes = ts.TotalMinutes;

Categories

Resources