How to make Visual Studio interpret an hour that is larger than 23hrs and smaller than 6hrs at the same time?

Asked

Viewed 299 times

-1

I have a function that is called and must enter the condition where the time now is greater than 23 hours and less than 6 hours at the same time, however the code conflicts with this condition and so never enters the condition.

Follows my code:

  string valor_horaC1 = horarioC1Label1.Text;//o valor na label é 23:00
   string valor_horaC2 = horarioC2Label1.Text;//o valor na label é 06:00
   var var_horaC1_2 = TimeSpan.Parse(valor_horaC1);
  var var_horaA2 = TimeSpan.Parse(valor_horaA2);



    if ((hora_now >= var_horaC1) && (hora_now <= var_horaC2)) //Condição para o Turno C
            {
                if (horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")
                {
                    label8.Text = "Turno 3";

                }

            }
  • yes I know I have to use the dates together but it turns out that the dates change as the hours go by

  • 1

    The confilt is not in condition but in the Types you are using... What is hora_now??? if you leave your variables with a more descriptive name or explain your logic better and what you are trying to do we can help more

  • @568lu Have any of the answers solved your question? Do you think you can accept one of them? See the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

5

First of all Visual Studio cannot do something like this because it is an IDE, it is a tool for writing code and it is not its function to calculate dates. But if you want to know how to program in C# to do this, you can answer.

I will ignore the mistakes that would give other types of problem and nor compile.

Already an error in this code because nothing guarantees that the data written in the text field will be in the correct format, if it is not your code will break. This can be seen in some questions like this: Convert string to Datetime.

Is there any reason to use a TimeSpan? Do you know what it’s for? Never use something you don’t know what it’s for and how to use it properly. If you want a time you shouldn’t use a TimeSpan because it is about a elapsed time and not a time (a point in the timeline).

Since there is no time-only type on . standard NET (some use auxiliary libraries to handle it) you would have to use a DateTime. But you can’t just consider hours anyway.

If you really want to use a precise time frame, it would be something like this:

using System;
using static System.Console;
                    
public class Program {
    public static void Main() {
        var horaC1 = new DateTime(2019, 1, 1, 23, 0, 0);
        var horaC2 = new DateTime(2019, 1, 2, 6, 0, 0);
        var now = new DateTime(2019, 1, 2, 5, 0, 0);
        if (now >= horaC1 && now <= horaC2 /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3");
        now = new DateTime(2019, 1, 2, 7, 0, 0);
        if (now >= horaC1 && now <= horaC2 /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3 ---");
    }
}

I commented on the part that I don’t have access, I changed the data to be fixed and had it printed just to facilitate the test.

If you want to insist on using the time interval, you can do:

using System;
using static System.Console;
                    
public class Program {
    public static void Main() {
        var horaC1 = new DateTime(2019, 1, 1, 23, 0, 0).TimeOfDay;
        var horaC2 = new DateTime(2019, 1, 2, 6, 0, 0).TimeOfDay;
        var now = new DateTime(2019, 1, 2, 5, 0, 0).TimeOfDay;
        if (now >= horaC1 || now <= horaC2 /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3");
        now = new DateTime(2019, 1, 2, 7, 0, 0).TimeOfDay;
        if (now >= horaC1 || now <= horaC2 /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3 ---");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If you do this, you are guaranteeing both at the same time, within the crooked logic you want to use. In your logic the time should be between 23 and 6 hours. So if you pass 23 is within the range you want, and if you have not yet reached 6 is also.

If you really want to use the && you have to reverse the logic:

using System;
using static System.Console;
                    
public class Program {
    public static void Main() {
        var horaC1 = new DateTime(2019, 1, 1, 23, 0, 0).TimeOfDay;
        var horaC2 = new DateTime(2019, 1, 2, 6, 0, 0).TimeOfDay;
        var now = new DateTime(2019, 1, 2, 5, 0, 0).TimeOfDay;
        if (!(now < horaC1 && now > horaC2) /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3");
        now = new DateTime(2019, 1, 2, 7, 0, 0).TimeOfDay;
        if (!(now < horaC1 && now > horaC2) /*&& horarioC1Label1.Text != "00:00" && horarioC2Label1.Text != "00:00")*/) WriteLine("Turno 3 ---");
    }
}

Much worse, right?

Note that all give the same result, what you want.

3

Try

if ((hora_now >= var_horaC1) || (hora_now <= var_horaC2)) {}

Because if hora_now is 5 in the morning, it will be less than var_horaC2 (6), but it will not be greater than var_horaC1 (23).

  • i need it to meet the conditions at the same time, the "or" does not work in this case

  • 2

    whereas hora_now is 5 o'clock in the morning, there is no way it can be at the same time greater than 23 o'clock and less than 6. 5 < 6 < 23.

  • 2

    If it were 10 o'clock in the morning it would not be less than 6 and not more than 23 and the if would give false and would not execute the code inside the if

-2

Let me give you an example in JS that is readily executable to illustrate that you need || instead of &&.

document.write("<h1>Com &&, que é o caso original</h1>"); // Equivale a Console.WriteLine();

var i; // Declaração de i
var mensagem = "NTROU no if na hora "; // Declaração e atribuição de mensagem

// Vou passar pelas 24 horas do dia, em passos de uma em uma hora
for (i = 1; i <= 24; ++i)
{
    // AQUI ! if original: se a hora testada for antes que 6 e depois que 23
    if (i <= 6 && /*<<< atenção ao && aqui */ i >= 23)
    {
        // equivale a Console.WriteLine();
        document.write("<p style='color: green;'>E" + mensagem + i + "</p>");
    }
    else
    {
        // Equivale a Console.WriteLine();
        document.write("<p style='color: red;'>NÃO E" + mensagem + i + "</p>");
    }
}

// Equivale a Console.WriteLine("-------------");
document.write("<hr/>");
document.write("<h1>Com ||</h1>"); // Equivale a Console.WriteLine();

// Mesma coisa do for anterior, vou varrer as 24 horas do dia em passos de 1 em 1 hora
for (i = 1; i <= 24; ++i)
{    
    // AQUI! if proposto: se a hora testada for menor que 6 OU maior que 23
    if (i <= 6 || /*<<< atenção ao || aqui */ i >= 23)
    {
        // Equivale a Console.WriteLine();
        document.write("<p style='color: green'>E" + mensagem + i + "</p>");
    }
    else
    {
        // Equivale a Console.WriteLine();
        document.write("<p style='color: red'>NÃO E" + mensagem + i + "</p>");
    }
}

If you don’t like JS or have plenty of time to copy and paste and run the program below and want an illustrative example, like see to believe, why the operator should be ||, in C#, below (also available at https://rextester.com/ECQM6018):

using System;

public class Program
{
    public static void Main(string[] args)
    {
        var corPadrao = Console.ForegroundColor;

        Console.ForegroundColor = ConsoleColor.Blue; 
        Console.WriteLine("Com &&, que é o original");
        Console.ForegroundColor = corPadrao;

        DateTime todayAtMidnight = DateTime.Now.Date;
        DateTime c1 = todayAtMidnight.AddHours(23);
        DateTime c2 = todayAtMidnight.AddHours(6);

        for (int i = 1; i <= 24; ++i)
        {
            DateTime testableTime = todayAtMidnight.AddHours(i);

            if (testableTime >= c1 && testableTime <= c2)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"ENTROU no if na hora {i}");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"NÃO ENTROU no if na hora {i}");
            }
        }

        Console.ForegroundColor = corPadrao;
        Console.WriteLine("---------------");
        Console.ForegroundColor = ConsoleColor.Blue; 
        Console.WriteLine("Com ||");

        for (int i = 1; i <= 24; ++i)
        {
            DateTime testableTime = todayAtMidnight.AddHours(i);

            if (testableTime >= c1 || testableTime <= c2)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"ENTROU no if na hora {i}");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"NÃO ENTROU no if na hora {i}");
            }
        }
    }
}

To transform the hour you’re in Label for the guy DateTime, do the following (this code below is C#/. NET even, before they complain):

var now = DateTime.Now;
var var_horaC1 = now.Date + TimeSpan.Parse(valor_horaC1);
var var_horaC2 = now.Date + TimeSpan.Parse(valor_horaC2);
...
if ((now >= var_horaC1 || now <= var_horaC2) &&
    (var_horaC1 - var_horaC2 != TimeSpan.Zero))
{
    // É o Turno 3.
}
  • 3

    The answer although conceptually ok, as it states that it gives an example in JS, does not apply to the question that was specifically asked about how to accomplish this in C#. I won’t even mention the obvious differences and the care that needs to be taken between programming in C# and JS. I believe you could have taken a look at the syntax of C# and used a REPL Online to validate if you thought it was interesting.

  • I put one up in your comment!

  • I wrote code C# in my answer, I don’t know if I erase or turn into JS?

  • 3

    I find it more interesting to erase and turn into C#. If you don’t want to miss what you did in JS, I suggest you make a Fiddle or save the code on Github and leave it in the format of a link like a reference. Something like "I also have a JS example available at link if you wish".

  • Cool, huh? Thanks for the touch.

  • 2

    Hi Marcelo, I deleted from the answer things that not only tarnish the answer. I suggest that the answers are focused only on the technical part and not on judgment about possible readers and their more or less busy life.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.