C
C#9mo ago
Mekasu0124

✅ Converting String To DateTimeOffset & Getting Average Days To Goal

public static string? CalculateDaysToGoal(string? startDate, string? endDate, string? hoursPerDay)
{
DateTimeOffset startDate = DateTimeOffset.Parse(startDate);
DateTimeOffset endDate = DateTimeOffset.Parse(endDate);
TimeSpan differenceInDays = endDate.Subtract(startDate);

string daysToGoal = Math.Ceil(differenceInDays / hoursPerDay).ToString();
return daysToGoal;
}
public static string? CalculateDaysToGoal(string? startDate, string? endDate, string? hoursPerDay)
{
DateTimeOffset startDate = DateTimeOffset.Parse(startDate);
DateTimeOffset endDate = DateTimeOffset.Parse(endDate);
TimeSpan differenceInDays = endDate.Subtract(startDate);

string daysToGoal = Math.Ceil(differenceInDays / hoursPerDay).ToString();
return daysToGoal;
}
I started a new thread as this is a new thing. I need to create a helper function that takes in 3 parameters to calculate the number of days the user needs to spend coding based off the number of hours per day they want to put towards this goal in order to get the number of days it will take them to achieve said goal. I've never done this before, not even in Python, so I have no idea how to start or what to do. Thanks in advance Edit: I started giving it a shot, and this is where I'm at
69 Replies
Pobiega
Pobiega9mo ago
Why is hoursperday a string? That seems silly
Mekasu0124
Mekasu01249mo ago
public class Goal
{
public int Id { get; set; }
public string Name { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string DaysToGoal { get; set; }
public string HoursPerDay { get; set; }
public string Achieved { get; set; }
}
public class Goal
{
public int Id { get; set; }
public string Name { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string DaysToGoal { get; set; }
public string HoursPerDay { get; set; }
public string Achieved { get; set; }
}
Pobiega
Pobiega9mo ago
Again, why is it a string? Use the correct data types everywhere
Mekasu0124
Mekasu01249mo ago
my database stores string so I'm using string
Angius
Angius9mo ago
Why does your database store it as strings...?
Pobiega
Pobiega9mo ago
Yeah, that just means you have one more place it's stored incorrectly
Mekasu0124
Mekasu01249mo ago
it's not "stored incorrectly" just because I chose to convert my information to strings. They're easier for me to handle and work with when it comes to formatting and such for console display so instead of trying to convert everything when I'm ready to display, it's already stored as needed
Pobiega
Pobiega9mo ago
Yes it is.
Angius
Angius9mo ago
It absolutely is
Mekasu0124
Mekasu01249mo ago
but give me 20 minutes and I'll delete my database file, redo all of my stuff to "the correct types" and put information back in
Pobiega
Pobiega9mo ago
I'm sorry to be blunt, but you will write better code this way It's honestly quite frustrating helping you, as you very often "fight back" against the suggestions you yourself ask for, given by people with many many years of professional experience.
Jimmacle
Jimmacle9mo ago
formatting and parsing should be processes outside of code that does the actual "work" also, as someone who inherited a database that stores everything as text instead of correct data types it will bite you later
Mekasu0124
Mekasu01249mo ago
I had a response typed, but honestly it's just not worth it. The position I'm in is either to conform to everyone else, or don't and if I don't then I get threatened with not getting help, or getting questioned about my code that has nothing to do with the question I asked. I understand that there's a preferred method and a preferred way of doing things, but at the end of the day it's my code and I'm responsible for it. I don't work for any major companies and I do this as a hobby just to learn things while I'm in school. Sorry to waste everyone's time, but I'm not the conform-to-everyone type. Sorry to waste your time
Jimmacle
Jimmacle9mo ago
doesn't proper database design (or data modeling in general) fall under "learn things?"
Angius
Angius9mo ago
"Hey, I used the garden hose to fill up my car with water instead of fuel, and now the lights don't work. How do I change the lightbulb?" Of course people will question why you filled your car's gas tank with water And will, rightfully, recommend to not do so
Pobiega
Pobiega9mo ago
And when we suggest something and you say "no, give me a new suggestion, one that better adheres to my ideas of what is correct" that... well it kills all enthusiasm I have for helping Because like it or not, you're in the wrong here, and then blaming us/me for not wanting to help when you obviously don't care about what we say, only that we fix your program...
Mekasu0124
Mekasu01249mo ago
never said I wasn't in the wrong and never blamed anyone
Pobiega
Pobiega9mo ago
I've probably personally spent close to 20 hours helping you. Why do you think I did that?
Jimmacle
Jimmacle9mo ago
also, fwiw this code does have a lot to do with the question you asked because it's causing problems when you're trying to do calculations and you have strings instead of proper dates/numbers if you get to a point where you have more complex SQL queries that filter based on these columns you will run into additional issues
Pobiega
Pobiega9mo ago
Yeah, strings can't be compared easily, or have math done on it And databases are really good at doing comparisons
Mekasu0124
Mekasu01249mo ago
well to render this all mute so everyone can continue with their day instead of being busy debating with me, I never fought back. That's just how it was viewed and taken. All I did was state that I store my information as string as it's easier for me to work with. I never blamed anyone, I just stated that my code gets questioned about things that have nothing to do with my question. As far as conforming to the "like mindset", even though I'm not that type of person, I've gone in and changed my data types in my code. I just have to do it on database creation. As per being in the wrong, I never said I wasn't. As far as everything else, it is what it is. Again, I've gone back and changed the data types and will figure it out from there. Thanks and sorry to be such a headache to everyone
Jimmacle
Jimmacle9mo ago
redoing code isn't a big deal and doesn't make you some kind of "conformist" since that seems to be the pain point for you like, i just spent all afternoon ripping out what i thought was a great system at the time but it turned out to be shit
Pobiega
Pobiega9mo ago
We spend more rime changing existing code than adding new for sure
Jimmacle
Jimmacle9mo ago
also especially in programming, if everyone is doing something a certain way that's probably an indicicator that it's a good way to do it that's why there are so many memes about stealing code, code you didn't write, etc
Mekasu0124
Mekasu01249mo ago
^ that's part of the reason I don't write my code like a vast majority of other programmers do. It helps prevent that
Jimmacle
Jimmacle9mo ago
prevents what?
Mekasu0124
Mekasu01249mo ago
stealing code
Jimmacle
Jimmacle9mo ago
how? and would you rather write lower quality code just so nobody wants to "steal" it?
Angius
Angius9mo ago
I mean, I guess people are less likely to steal a rusted Multipla with missing doors than they are to steal a brand new Rivian... But if you're writing the Multipla of code, it's unlikely it's even worth stealing it in the first place
Jimmacle
Jimmacle9mo ago
(which seems against your best interests if your goal is to learn)
Angius
Angius9mo ago
Yeah
Jimmacle
Jimmacle9mo ago
if you have an application that is valuable enough to steal, you use legal options to deal with it the style of code won't stop anyone
Mekasu0124
Mekasu01249mo ago
well like I said before, I went back and changed my data types, and worked through figuring out the conversion myself and I have this for the code
public static double CalculateHoursPerDay(string? startDate, string? endDate, double hoursPerDay)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);
TimeSpan dtg = difference.Divide(hoursPerDay);

double daysToGoal = Convert.ToDouble(dtg.TotalDays);
return daysToGoal;
}
public static double CalculateHoursPerDay(string? startDate, string? endDate, double hoursPerDay)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);
TimeSpan dtg = difference.Divide(hoursPerDay);

double daysToGoal = Convert.ToDouble(dtg.TotalDays);
return daysToGoal;
}
Angius
Angius9mo ago
So, we have the amount of hours they want to work per day... but we don't heve the total amount of hours necessary to complete the task
Mekasu0124
Mekasu01249mo ago
I don't need that part. I just needed the user's input of how many hours per day they wanted to work and then return the number of days it'll take to complete based off that input
Angius
Angius9mo ago
Yeah, aight, but... how do you plan to calculate it?
Mekasu0124
Mekasu01249mo ago
that's in the code block
Angius
Angius9mo ago
Right So you get the amount of time between two days Then you divide it by how much time per day the developer can write code And what you get back is...?
Mekasu0124
Mekasu01249mo ago
a double
Angius
Angius9mo ago
Well, yeah But it's not days It's not hours It's "units of coding"? "Sprints"? It can't be any unit of time, because the amount of time from start date to end date is fixed
MODiX
MODiX9mo ago
Mekasu0124
REPL Result: Success
static double CalculateDaysToGoal(string? startDate, string? endDate, double hoursPerDay)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);
TimeSpan dtg = difference.Divide(hoursPerDay);

double daysToGoal = Convert.ToDouble(dtg.TotalDays);
return daysToGoal;
}

string? startDate = "10/4/2023";
string? endDate = "10/30/2023";
double hoursPerDay = 8;
double daysToGoal = CalculateDaysToGoal(startDate, endDate, hoursPerDay);

Console.WriteLine(daysToGoal);
static double CalculateDaysToGoal(string? startDate, string? endDate, double hoursPerDay)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);
TimeSpan dtg = difference.Divide(hoursPerDay);

double daysToGoal = Convert.ToDouble(dtg.TotalDays);
return daysToGoal;
}

string? startDate = "10/4/2023";
string? endDate = "10/30/2023";
double hoursPerDay = 8;
double daysToGoal = CalculateDaysToGoal(startDate, endDate, hoursPerDay);

Console.WriteLine(daysToGoal);
Console Output
3.25
3.25
Compile: 731.908ms | Execution: 59.567ms | React with ❌ to remove this embed.
Mekasu0124
Mekasu01249mo ago
this returns 3.25 days until the goal is achieved
Angius
Angius9mo ago
Uh, no, it does not
Mekasu0124
Mekasu01249mo ago
ok yea I see that now
Angius
Angius9mo ago
It calculates how many times the developer has to sit down and work for hoursPerDay hours, to finish the project started at startDate by endDate
Mekasu0124
Mekasu01249mo ago
wait that's weeks. apologies. 3.25 weeks 30 - 4 = 26 days / 8 hrs/day = 3.25 weeks now I done got myself backwards.
Create the ability to set coding goals and show how far the users are from reaching their goal, along with how many hours a day they would have to code to reach their goal. You can do it via SQL queries or with C#.
Create the ability to set coding goals and show how far the users are from reaching their goal, along with how many hours a day they would have to code to reach their goal. You can do it via SQL queries or with C#.
this is the challenge that's supposed to match, but I've got myself backwards ok so I'm requesting the user's input for the start and end date of the goal
Angius
Angius9mo ago
Yep and hours per day is the output, not the input
Mekasu0124
Mekasu01249mo ago
public static double DaysToGoal(string? startDate, string? endDate)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);

double daysToGoal = Convert.ToDouble(difference.TotalDays);
return daysToGoal;
}
public static double DaysToGoal(string? startDate, string? endDate)
{
DateTimeOffset start = DateTimeOffset.Parse(startDate);
DateTimeOffset end = DateTimeOffset.Parse(endDate);

TimeSpan difference = end.Subtract(start);

double daysToGoal = Convert.ToDouble(difference.TotalDays);
return daysToGoal;
}
I'm returning the days until the end of the goal here so that they know how long they have until the end of the goal
Angius
Angius9mo ago
Yeah
Mekasu0124
Mekasu01249mo ago
these are the requirements. I've fulfilled all of those
No description
Mekasu0124
Mekasu01249mo ago
these are the challenges to the project. I've got the first one done
No description
Mekasu0124
Mekasu01249mo ago
so the trick with the bottom part
Create the ability to set coding goals and show how far the users are from reaching their goal, along with how many hours a day they would have to code to reach their goal. You can do it via SQL queries or with C#
since I am storing
public class Goal
{
public int? Id { get; set; }
public string? Name { get; set; }
public string? StartDate { get; set; }
public string? EndDate { get; set; }
public double? DaysToGoal { get; set; }
public double? HoursPerDay { get; set; }
public string? Achieved { get; set; }
}
public class Goal
{
public int? Id { get; set; }
public string? Name { get; set; }
public string? StartDate { get; set; }
public string? EndDate { get; set; }
public double? DaysToGoal { get; set; }
public double? HoursPerDay { get; set; }
public string? Achieved { get; set; }
}
the DaysToGoal and HoursPerDay in the database, I'll need to have a check system that checks the current date against the end date so that it can update the database once per day to keep the DaysToGoal and HoursPerDay updated so that when the user selects the menu option View All Goals, that information is updated accurately but it doesn't say anything about setting a limit on the user of how many days they should or can spend coding so the hours per day would just be done with a number that I choose to base it off of, right?
Angius
Angius9mo ago
The way I understand it, the goal is something like "between today and next week I want to spend 60 hours doing X" Then you need to calculate how many hours each day will the user need to spend to meet this goal
Mekasu0124
Mekasu01249mo ago
ok. I can see that. The way that I'm understanding it though is 1. Create the ability to set coding goals and show how far the users are from reaching their goal so get user input of start and end date for goal and return number of days in between 2. along with how many hours a day they would have to code to reach their goal is quite open-ended. We can't control how long a person wants to spend coding, so either set a limit or base if off of like 8 or 10 hours spent per day.
Angius
Angius9mo ago
Well, no, we can't control it But we can tell them how many hours they would need to work Say, the goal is to workout 10 hours in 5 days That would mean the user will need to workout for 2 hours a day
Mekasu0124
Mekasu01249mo ago
so I still need to get the number of hours the user wants to work as a user input?
Angius
Angius9mo ago
The total amount of hours, yes At least to my understanding
Mekasu0124
Mekasu01249mo ago
ok so I've asked the user for the Goal Name, Start Date, End Date, and Hours Per Day. I've calculated and returned an integer instead of a double on the number of days until the goal is complete so with them deciding on how many hours per day they want to spend coding, there's nothing left for me to do except write a method that checks todays date against the end date of each goal in the database, and updates the Days Until Goal count so that when the user wants to view all of their goals, the information is accurate I have a question if that's alright do you mind if I dm you? it's harmless. promise
Angius
Angius9mo ago
Sure Ah, no, my DMs stay closed
Mekasu0124
Mekasu01249mo ago
oh ok. no problem. I wanted to ask if you'd be willing to do a code review on something else that I built. It's a console based trivia game and I'm a bit shakey on it that's what I was gonna dm you. I just didn't want anyone to do a code review and then I have to filter through multiple reviews
Angius
Angius9mo ago
There's #code-review if you need it
Mekasu0124
Mekasu01249mo ago
I appreciate it. I just wanted one person to do a review, but I'll take a look at the channel ok so I've ran into another problem and I'm not quite sure how to fix it
Console.WriteLine("\nWhen Editing Information, if you want it left the same then press ENTER to skip it.");
Console.WriteLine("\nCurrent Start Date: {currentGoal.StartDate}");
Console.Write("Enter Corrected Start Date: ");

string? input = Console.ReadLine();
string? newStartDate = UserValidation.VerifyEmptyOrChanged(
currentGoal.StartDate,
UserValidation.VerifyDateInput(input));
Console.WriteLine("\nWhen Editing Information, if you want it left the same then press ENTER to skip it.");
Console.WriteLine("\nCurrent Start Date: {currentGoal.StartDate}");
Console.Write("Enter Corrected Start Date: ");

string? input = Console.ReadLine();
string? newStartDate = UserValidation.VerifyEmptyOrChanged(
currentGoal.StartDate,
UserValidation.VerifyDateInput(input));
When going through testing, I get this back as a return
-------------------------
Goal Name: An Edited Test Goal
Start Date: 01/01/0001
End Date: 01/01/0001
Coding Hours Per Day: 6
Days Until Goal: 0
Goal Achieved: No
-------------------------
-------------------------
Goal Name: An Edited Test Goal
Start Date: 01/01/0001
End Date: 01/01/0001
Coding Hours Per Day: 6
Days Until Goal: 0
Goal Achieved: No
-------------------------
is something wrong with my validation? also, tbh, it's my first time doing variables with question marks to negate null information. idk if that helps at all I'm going to go through and remove all of the ? from my code. I'm not entirely sure on how/when to use them, so I'm just not goign to use them yet
Angius
Angius9mo ago
C# expects the date to be in a specific format ISO8601 to be more precise So yyyy-MM-dd HH:mm
Mekasu0124
Mekasu01249mo ago
that's my bad. I didn't share all the code
public static string VerifyDateInput(string input)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "MM/dd/yyyy";
DateTimeStyles style = DateTimeStyles.None;
DateTimeOffset result;

while (!DateTimeOffset.TryParseExact(input, format, provider, style, out result) && !String.IsNullOrEmpty(input))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Input Must Be In Format: MM/DD/YYYY");

Console.ForegroundColor = ConsoleColor.White;
Console.Write("Enter Corrected Date: ");

input = Console.ReadLine();
}

return result.ToString(format);
}
public static string VerifyDateInput(string input)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "MM/dd/yyyy";
DateTimeStyles style = DateTimeStyles.None;
DateTimeOffset result;

while (!DateTimeOffset.TryParseExact(input, format, provider, style, out result) && !String.IsNullOrEmpty(input))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Input Must Be In Format: MM/DD/YYYY");

Console.ForegroundColor = ConsoleColor.White;
Console.Write("Enter Corrected Date: ");

input = Console.ReadLine();
}

return result.ToString(format);
}
public static string VerifyEmptyOrChanged(string oldEntry, string newEntry)
{
if (String.IsNullOrEmpty(newEntry) || newEntry == oldEntry)
{
return oldEntry;
}
else
{
return newEntry;
}
}
public static string VerifyEmptyOrChanged(string oldEntry, string newEntry)
{
if (String.IsNullOrEmpty(newEntry) || newEntry == oldEntry)
{
return oldEntry;
}
else
{
return newEntry;
}
}
if the user presses enter to leave the current value the same, it's supposed to return the current value this is the user entry part full code https://pastebin.com/GsrdbkXr
Pobiega
Pobiega8mo ago
Interesting. Even with passing format as MM/dd/yyyy this actually formats the date in a different format
No description
Mekasu0124
Mekasu01248mo ago
right and even with removing all of my ?'s from various variables and parameters that I was using them in, still didn't fix it. It's still returning 01/01/0001
Pobiega
Pobiega8mo ago
please tell me you didnt actually do that you just ruined your null annotations writing them as you write code is fine, putting them in on existing code is a painful process
Jimmacle
Jimmacle8mo ago
also, unless you have enabled nullable warnings as errors they don't really affect the compilation/behavior of your code so i wouldn't expect anything to change regardless their purpose is to help you avoid null references in places they shouldn't be allowed (for reference types, anyway)
Mekasu0124
Mekasu01248mo ago
I can put them back no problem so I've got it all put back. With my issue of the date thing though, I think my solution is to break those back out. So instead of having
string? newStartDate = UserValidation.VerifyEmptyOrChanged(
currentGoal.StartDate,
UserValidation.VerifyDateInput(input));
string? newStartDate = UserValidation.VerifyEmptyOrChanged(
currentGoal.StartDate,
UserValidation.VerifyDateInput(input));
I should have
input = Console.ReadLine();
string? newStartDate = UserValidation.VerifyEmptyOrChanged(input);
newStartDate = UserValidation.VerifyDateInput(newStartDate);
input = Console.ReadLine();
string? newStartDate = UserValidation.VerifyEmptyOrChanged(input);
newStartDate = UserValidation.VerifyDateInput(newStartDate);
or I could have VerifyEmptyOrChanged return a true/false condition like
public static bool VerifyEmptyOrChanged(string? oldEntry, string? newEntry)
{
if (String.IsNullOrEmpty(newEntry) || newEntry == oldEntry)
{
return true;
}
else
{
return false;
}

input = Console.ReadLine();
bool dateChanged = UserValidation.VerifyEmptyOrChanged(currentGoal.StartDate, input);
newStartDate = dateChanged ? UserValidation.VerifyDateInput(input) : currentGoal.StartDate;
public static bool VerifyEmptyOrChanged(string? oldEntry, string? newEntry)
{
if (String.IsNullOrEmpty(newEntry) || newEntry == oldEntry)
{
return true;
}
else
{
return false;
}

input = Console.ReadLine();
bool dateChanged = UserValidation.VerifyEmptyOrChanged(currentGoal.StartDate, input);
newStartDate = dateChanged ? UserValidation.VerifyDateInput(input) : currentGoal.StartDate;
I'll be back later. I have to go take a midterm
static bool VerifyChanged(string? old, string? newI)
{
return (String.IsNullOrEmpty(newI) || newI == old) ? false : true;
}

static string? VerifyDateInput(string? input)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "MM/dd/yyyy";
DateTimeStyles style = DateTimeStyles.None;
DateTimeOffset result;

while (!DateTimeOffset.TryParseExact(input, format, provider, style, out result) && !String.IsNullOrEmpty(input))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Input Must Be In Format: MM/DD/YYYY");

Console.ForegroundColor = ConsoleColor.White;
Console.Write("Enter Corrected Date: ");

input = Console.ReadLine();
}

return result.ToString(format);
}

string? currentDate = "01/01/0001";
string? input = "02/02/0002";

bool nameChanged = VerifyChanged(currentDate, input);

string? newDate = nameChanged ? VerifyDateInput(input) : currentDate;

Console.WriteLine(newDate);
static bool VerifyChanged(string? old, string? newI)
{
return (String.IsNullOrEmpty(newI) || newI == old) ? false : true;
}

static string? VerifyDateInput(string? input)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "MM/dd/yyyy";
DateTimeStyles style = DateTimeStyles.None;
DateTimeOffset result;

while (!DateTimeOffset.TryParseExact(input, format, provider, style, out result) && !String.IsNullOrEmpty(input))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Input Must Be In Format: MM/DD/YYYY");

Console.ForegroundColor = ConsoleColor.White;
Console.Write("Enter Corrected Date: ");

input = Console.ReadLine();
}

return result.ToString(format);
}

string? currentDate = "01/01/0001";
string? input = "02/02/0002";

bool nameChanged = VerifyChanged(currentDate, input);

string? newDate = nameChanged ? VerifyDateInput(input) : currentDate;

Console.WriteLine(newDate);
so I did some playground testing, and have decided to turn the function that checks null or empty and if the conditions match into a boolean return. This actually returns what is expected given different conditions. So now to implement it into the program and test it with those conditions sorry to bother you, however, I need a smidge of help. I'm trying to mock up getting the total time and average time of coding sessions in my database. I've created a small mock session, but I'm getting format issues from my second function https://pastebin.com/hw8dd8wX would you mind to take a look? nvm I got it ok so I don't got it
static double CalculateAverageSession(List<CodeSession?>? allSessions)
{
List<double> values = GetTotalSessionTime(allSessions);

double totalSeconds = 0;

foreach (double value in values)
{
totalSeconds = totalSeconds + value;
}

double averateTime = totalSeconds / values.Count;

TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
string str = time.ToString(@"hh\:mm\:ss");

Console.WriteLine("Total Time: {0}", str);
return averateTime;
}

static List<double> GetTotalSessionTime(List<CodeSession?>? allSessions)
{
List<double> values = new();

string format = @"hh\:mm";
CultureInfo provider = CultureInfo.InvariantCulture;

foreach (CodeSession session in allSessions)
{
TimeSpan startTime;
TimeSpan endTime;

TimeSpan start = TimeSpan.ParseExact(session.StartTime, format, provider);
TimeSpan end = TimeSpan.ParseExact(session.EndTime, format, provider);
TimeSpan difference = end.Subtract(start);

double timeInSeconds = difference.TotalSeconds;

values.Add(timeInSeconds);
}

return values;
}

List<CodeSession?>? allSessions = new() {};


CodeSession? session = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "08:00", EndTime = "12:00", Duration = "04:00:00" };
CodeSession? session1 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "09:00", EndTime = "13:00", Duration = "04:00:00" };
CodeSession? session2 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "10:00", EndTime = "14:00", Duration = "04:00:00" };
CodeSession? session3 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "11:00", EndTime = "15:00", Duration = "04:00:00" };
CodeSession? session4 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "12:00", EndTime = "16:00", Duration = "04:00:00" };
CodeSession? session5 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "13:00", EndTime = "17:00", Duration = "04:00:00" };
CodeSession? session6 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "14:00", EndTime = "18:00", Duration = "04:00:00" };

allSessions.Add(session);
allSessions.Add(session1);
allSessions.Add(session2);
allSessions.Add(session3);
allSessions.Add(session4);
allSessions.Add(session5);
allSessions.Add(session6);

double averageTime = CalculateAverageSession(allSessions);

TimeSpan time = TimeSpan.FromSeconds(averageTime);
string str = time.ToString(@"hh\:mm\:ss");

Console.WriteLine("Average Time: {0}", str);

class CodeSession
{
public int? Id { get; set; }
public string? TodaysDate { get; set; }
public string? StartTime { get; set; }
public string? EndTime { get; set; }
public string? Duration { get; set; }
}
static double CalculateAverageSession(List<CodeSession?>? allSessions)
{
List<double> values = GetTotalSessionTime(allSessions);

double totalSeconds = 0;

foreach (double value in values)
{
totalSeconds = totalSeconds + value;
}

double averateTime = totalSeconds / values.Count;

TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
string str = time.ToString(@"hh\:mm\:ss");

Console.WriteLine("Total Time: {0}", str);
return averateTime;
}

static List<double> GetTotalSessionTime(List<CodeSession?>? allSessions)
{
List<double> values = new();

string format = @"hh\:mm";
CultureInfo provider = CultureInfo.InvariantCulture;

foreach (CodeSession session in allSessions)
{
TimeSpan startTime;
TimeSpan endTime;

TimeSpan start = TimeSpan.ParseExact(session.StartTime, format, provider);
TimeSpan end = TimeSpan.ParseExact(session.EndTime, format, provider);
TimeSpan difference = end.Subtract(start);

double timeInSeconds = difference.TotalSeconds;

values.Add(timeInSeconds);
}

return values;
}

List<CodeSession?>? allSessions = new() {};


CodeSession? session = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "08:00", EndTime = "12:00", Duration = "04:00:00" };
CodeSession? session1 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "09:00", EndTime = "13:00", Duration = "04:00:00" };
CodeSession? session2 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "10:00", EndTime = "14:00", Duration = "04:00:00" };
CodeSession? session3 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "11:00", EndTime = "15:00", Duration = "04:00:00" };
CodeSession? session4 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "12:00", EndTime = "16:00", Duration = "04:00:00" };
CodeSession? session5 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "13:00", EndTime = "17:00", Duration = "04:00:00" };
CodeSession? session6 = new() { Id = 1, TodaysDate = "10/05/2023", StartTime = "14:00", EndTime = "18:00", Duration = "04:00:00" };

allSessions.Add(session);
allSessions.Add(session1);
allSessions.Add(session2);
allSessions.Add(session3);
allSessions.Add(session4);
allSessions.Add(session5);
allSessions.Add(session6);

double averageTime = CalculateAverageSession(allSessions);

TimeSpan time = TimeSpan.FromSeconds(averageTime);
string str = time.ToString(@"hh\:mm\:ss");

Console.WriteLine("Average Time: {0}", str);

class CodeSession
{
public int? Id { get; set; }
public string? TodaysDate { get; set; }
public string? StartTime { get; set; }
public string? EndTime { get; set; }
public string? Duration { get; set; }
}
so I'm trying to get all of the session durations, add them together and show the total time and then take that total time and divide it by the number of durations to get the average total time between all the sessions, but I just keep getting "04:00:00 for both print statements. ok so I'm actually just an idiot. There's nothing wrong with the conversions. I thought there was because each session has the same time duration. 4 hours time 7 sessions is 100,800 and then divide that by 7 and you get 14,400 back which is 4 hours
Want results from more Discord servers?
Add your server
More Posts