I wanted to create a readonly struct that represents time in 24-hour format, so it has a method that is supposed to return a string of time (for example: "08:45" if 8 and 45 were passed respectively or "03:40" if 25 hours and 160 minutes were passed)
The problem is in the method, how do I return a string with values from the object inserted into it? I imagined something like return "0{stringtimeobj.hours}:0{stringtimeobj.minutes} but I can't really figure out how to format a string so that it has values from an object in it. Please help out!
using System;
namespace TimeStruct
{
public readonly struct Time
{
private readonly int hours2;
private readonly int minutes2;
public Time(int minutes)
: this()
{
this.minutes2 = minutes;
}
public Time(int hours, int minutes)
{
this.hours2 = hours;
this.minutes2 = minutes;
}
public int Hours
{
get
{
if (this.hours2 < 24)
{
return this.minutes2;
}
else if (this.hours2 == 24)
{
return 0;
}
else
{
double overflowtohours = ((Math.Truncate((double)this.minutes2 / 60) + 1) * 60) - 60;
return Convert.ToInt32(this.hours2 - ((Math.Truncate((double)(Convert.ToInt32(overflowtohours / 60) + this.hours2) / 24) + 1) * 24) - 24);
}
}
}
public int Minutes
{
get
{
if (this.minutes2 < 60)
{
return this.minutes2;
}
else if (this.minutes2 == 60)
{
return 0;
}
else
{
double overflowtohours = ((Math.Truncate((double)this.minutes2 / 60) + 1) * 60) - 60;
return Convert.ToInt32(this.minutes2 - overflowtohours);
}
}
}
public string ToString(int hours3, int minutes3)
{
Time stringtimeobj = new Time(hours3, minutes3);
return /* string "00:00" with hour and minute values from object stringtimeobj inserted */
}
}
}
ToStringparameterized? Normally you'd have a parameterless method that uses the data in the object you're calling it on.%(modulo) operatorsomeInt. ToString("00")will add leading zero as needednew Time(5, 10).ToString()for example - and that should format 5 hours and 10 minutes.