Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify if else condition using timespan in C#

Tags:

c#

timespan

I have to create a real time report. For that, I have to write conditions for each and every hour of a given day. In the code below, the condition checks for the current day of week and then check for the current time and based on that a report has to be generated.

protected void sample()
{
    TimeSpan zerothHour = new TimeSpan(00, 0, 0);
    TimeSpan firstHour = new TimeSpan(01, 0, 0);
    TimeSpan secondHour = new TimeSpan(02, 0, 0);
    TimeSpan thirdHour = new TimeSpan(03, 0, 0);
    TimeSpan fourthHour = new TimeSpan(04, 0, 0);
    TimeSpan fifthHour = new TimeSpan(05, 0, 0);
    TimeSpan sixthHour = new TimeSpan(06, 0, 0); 
    // and so on until the twentyfourth hour
    if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
    {
        if (DateTime.Now.TimeOfDay >= sixthHour && DateTime.Now.TimeOfDay <= seventhHour)
        {
            //MySql query here
            string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            MySqlConnection connection = new MySqlConnection(MyConString);
            string agentlogin = "SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND shift IN('6:00-15-00', '22:00-7:00') AND Mon = 'W'";
            MySqlCommand cmd = new MySqlCommand(agentlogin, connection);
            connection.Open();
            MySqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
               //lblagentlogin.Text += rdr["agentlogin"] + Environment.NewLine;
                sqlList.Add(Convert.ToString(rdr["agentlogin"]));
            }
        }
        else if(DateTime.Now.TimeOfDay >= seventhHour && DateTime.Now.TimeOfDay <= eigthHour)
        {

        }
        else if (DateTime.Now.TimeOfDay >= eigthHour && DateTime.Now.TimeOfDay <= ninthHour)
        {

        }
        else if (DateTime.Now.TimeOfDay >= ninthHour && DateTime.Now.TimeOfDay <= tenthHour)
        {

        }
        else if (DateTime.Now.TimeOfDay >= tenthHour && DateTime.Now.TimeOfDay <= eleventhHour)
        {

        }
        // and so on for the entire cycle of time
    }
}

The code above is only for Monday and I have to do the same thing for the other six days of week too. When I add the queries inside each conditions, it would be like hundreds of lines.

Is there a better way to get this done without having to write hundreds of lines of code?

like image 491
prkash Avatar asked Oct 29 '18 08:10

prkash


People also ask

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property. Save this answer.

How do you declare a TimeSpan?

By calling one of its explicit constructors. The following example initializes a TimeSpan value to a specified number of hours, minutes, and seconds. TimeSpan interval = new TimeSpan(2, 14, 18); Console. WriteLine(interval.

What is TimeSpan datatype?

TimeSpan (amount of time) is a new data type that can be used to store information about an elapsed time period or a time span. For example, the value in the picture (148:05:36.254) consists of 148 hours, 5 minutes, 36 seconds, and 254 milliseconds.

How does TimeSpan work C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


3 Answers

Does this work for you?

var sqls = new []
{
    "select x from y",
    "select w from q",
    // etc - 24 options
};

var sql = sqls[DateTime.Now.Hour];

Or even:

var sqls = new Action[]
{
    () => { /* sql for midnight */ },
    () => { /* sql for 1 am */ },
    // etc
    () => { /* sql for 11 pm */ },
};

var sql = sqls[DateTime.Now.Hour];

sql.Invoke();

If you want DayOfWeek and Hour then you could use this:

var sqls = new string[][]
{
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
};

var sql = sqls[(int)DateTime.Now.DayOfWeek][DateTime.Now.Hour];

Based on the comments and other answers, here's a more succinct way of doing it:

string day = DateTime.Now.DayOfWeek.ToString().Substring(0, 3);

string[] shifts = new []
{
    "('22:00-7:00')",
    "('22:00-7:00', '6:00-15:00')",
    // 24
};

string shift = shifts[DateTime.Now.Hour];

string sql = $"SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND shift IN {shifts} AND {day} = 'W'";
like image 119
Enigmativity Avatar answered Oct 21 '22 16:10

Enigmativity


It sounds like you can vastly simplify your code by generating your SQL dynamically. I am guessing a bit as I don't know your data model fully, but something along the following:

var dayColumns = new [] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
var currentDayColumn = dayColumns[(int) DateTime.Now.DayOfWeek];

string shifts;

switch (DateTime.Now.Hour) {
  case 0:
    shifts = "('22:00-7:00')"
    break;
  case 6:
    shifts = "('22:00-7:00', '6:00-15:00')"
    break;
  //TODO - more cases
}

string sql = "SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND shift IN " + shifts + " AND " + currentDayColumn + " = 'W'";

If you can change the shift to two columns with the start and end hours, you can optimise it further like this:

var hour = DateTime.Now.Hour

string sql = "SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND " + hour + " >= shift_start_hour AND " + hour + " < shift_end_hour AND " + currentDayColumn + " = 'W'";
like image 45
Jonas Høgh Avatar answered Oct 21 '22 14:10

Jonas Høgh


Assuming your SQL also depends on WeekDay + Hour (otherwise it wouldn't make much sense?) you can do something like this:

protected void sample()
{
    var now = DateTime.Now;
    var sql = GetSql(now.DayOfWeek, now.Hour);
    // execute sql
}

protected string GetSql(DayOfWeek dayofweek, int hour)
{
    // generate sql, using "(int)dayofweek" if needed
}
like image 35
Peter B Avatar answered Oct 21 '22 15:10

Peter B