Calculate average timespan - c#

I am to calculate average of a set of time spans, where each time span is a subtraction between two dates.
DateTime a = GetStartDateTime();
DateTime b = GetEndDateTime();
var delta = b.Subtract(a).TotalDays;
Date format is like 22.08.2016 21:00:00
Is there any way to do this more rationally?
Also, I am curious why my delta is always like 0.26914351851851853, in other words why it is not integer?
UPDATE:
Here is example time spans:
23.08.2016 10:31:38 - 22.08.2016 21:00:00
24.08.2016 14:32:26 - 24.08.2016 21:00:00
17.08.2016 8:36:51 - 01.01.2016 21:00:00
17.08.2016 8:34:27 - 15.03.2016 21:00:00

Perform a simple mean calculation across the Ticks value of all your TimeSpans and create a new TimeSpan from the result. That will represent the average or mean TimeSpan. e.g.
var timeSpanList = new List<TimeSpan>();
var provider = CultureInfo.InvariantCulture;
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("23.08.2016 10:31:38", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("22.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("24.08.2016 14:32:26", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("24.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:36:51", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("01.01.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:34:27", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("15.03.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
var totalTicks = 0L;
foreach(var ts in timeSpanList)
{
totalTicks += ts.Ticks;
}
var avgTicks = totalTicks / timeSpanList.Count;
var avgTimeSpan = new TimeSpan(avgTicks);

Related

String was not recognized as a valid DateTime in asp.net core 3

The date format in an excel upload is returning this error.
{"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."}
I was able to fix the issue before here on stackoverflow(Check code) but today while testing the upload again, the problem persists. I have checked almost all the suggestions available on StackOverflow but none seem to be working.
On the excel sheet I have 6/3/2020 but in the code I got 6/3/2020 12:00:00 AM
I have been trying to fix this all day
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
var date = workSheet.Cells[i, 3].Value.ToString();
//will throw exception if the fields in tenor are invalid
try
{
DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
validationResult.Message = "Invalid Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
}
else
{
validationResult.Message = "Empty Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
++row;
}
return validationResult;
}
OK, here's your line of code:
DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);
And here is the date string you are trying to convert:
"6/3/2020 12:00:00 AM"
Notice how the date string contains hours, minutes, and seconds, but your format string only has hours and minutes. DateTime.ParseExact needs you to supply the exact format of the incoming string.
Try add seconds to format of date:
Replace
DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm tt", CultureInfo.InvariantCulture);
with
DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

C# Date formatting issue

I have the following:
string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";
string from = "2016-06-20T16:20:00.0000000-04:00";
string to = "2016-06-21T16:21:00.0000000-04:00";
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;
Console.WriteLine(fromDate);
Console.WriteLine(toDate);
This prints out the Date without the hour and minutes. How do I make it work and show the time?
By using .Date you are selecting the date part only from the resulted DateTime object. So the default value for the time will be applied, Remove .Date then you will get the expected result;
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
This Example will show you the difference
You are calling .date which is selecting just the date part:
string from = "2016-06-20T16:20:00.0000000-04:00";
DateTime fromDateTime = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDateTime = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
Will produce:
> 6/20/2016 8:20:00 PM
> 6/21/2016 8:21:00 PM
Notice the lack of .Date on the end
What you have to do just remove your ending ".Date" from your code.
string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";
string from = "2016-06-20T16:20:00.0000000-04:00";
string to = "2016-06-21T16:21:00.0000000-04:00";
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
Console.WriteLine(fromDate);
Console.WriteLine(toDate);
Console.ReadLine();

how to convert timespan to string with format

I have timespan "1.00:00:11" and I would like to convert this to string:
"24:00" .As the code
DateTime date1 = Convert.ToDateTime("2014/12/12 14:37:56");
DateTime date2 = Convert.ToDateTime(("2014/12/13 14:37:59");
string minutes = (date2.Subtract(date1).TotalMinutes).ToString();
string result = TimeSpan.FromMinutes(Convert.ToDouble(minutes)).ToString();
I got result = "1.00:00:11".
How to change this result to (HH:mm).
And then I have a problem when I convert the string "24:00" to Datetime.
The Problem is:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
Is there some function?
To get the amount of time in hh:mm:ss format, you could do something as like,
DateTime date1 = Convert.ToDateTime("2014/12/12 14:37:56");
DateTime date2 = Convert.ToDateTime(("2014/12/13 14:37:59"));
double totalSec = date2.Subtract(date1).TotalSeconds;
string result = string.Format("{0:00}:{1:00}:{2:00}", totalSec / 3600, (totalSec / 60) % 60, totalSec % 60);
And this produces the quantity of time in hh:mm:ss format, it is not hh:mm:ss part of any specific day.
So you cannot directly convert it into datetime type. For datetime type max of hh:mm:ss is just 23:59:59.
To get the hh:mm:ss part of the timespan you can do this,
string result = date2.Subtract(date1).ToString("hh\\:mm\\:ss");
Hope this helps...

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

How to compare two DateTime to seconds?

How to compare two DateTime to seconds?
var date1 = DateTime.Now;
var date2 = new DateTime (1992, 6, 6);
var seconds = (date1 - date2).TotalSeconds;
Do you mean comparing two DateTime values down to the second? If so, you might want something like:
private static DateTime RoundToSecond(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day,
dt.Hour, dt.Minute, dt.Second);
}
...
if (RoundToSecond(dt1) == RoundToSecond(dt2))
{
...
}
Alternatively, to find out whether the two DateTimes are within a second of each other:
if (Math.Abs((dt1 - dt2).TotalSeconds) <= 1)
If neither of these help, please give more detail in the question.
If you subtract one date from another, it returns a TimeSpan which has a TotalSeconds property. So:
double seconds = (Date1 - Date2).TotalSeconds;
DateTime start = DateTime.now;
DateTime end = DateTime.end;
TimeSpan dif = end - start;
dif will be of the form 0:0:0:0 where the third value is seconds.

Categories