0

I made a script that check if the current time is equals to a string, the code is:

    string ore = Properties.Settings.Default.oreChiusura;
string minuti = Properties.Settings.Default.minutiChiusura;
var t1 = DateTime.Now.ToString("HH:mm");
var t2 = ore + ":" + minuti;

if(t1 == t2)
{
     //Stuff
}

the problem is, if "minuti" is like 01....09 it not work, it work only if is a number without the starting 0. What am I doing wrong?

3 Answers3

3

Your example is a perfect illustration to the principle that you should not be doing comparisons in strings if you can do them in integers:

var adesso = DateTime.Now;
var oreAdesso = adesso.Hour;
var minutiAdesso = adesso.Minute;
if (oreAdesso == ore && minutiAdesso == minuti) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Use this code:

string ore = Properties.Settings.Default.oreChiusura;
string minuti = Properties.Settings.Default.minutiChiusura;
var t1 = DateTime.Now.ToString("HH:mm");
var t2 = ore.PadLeft(2, '0') + ":" + minuti.PadLeft(2, '0');

if(t1 == t2)
{
     //Stuff
}

BUT! It is strongly advised to change your code to use TimeSpan setting instead of oreChiusura and minutiChiusura settings, and then compare TimeSpan values instead of strings.

For example:

var t1 = DateTime.Now.TimeOfDay;
var t2 = Properties.Settings.Default.Chiusura;
if(t1 == t2)
{
     //Stuff
}
Dusan
  • 5,000
  • 6
  • 41
  • 58
0

You can achieve it by casting ore and minuti to int, and then comparing the values.

int ore = Convert.ToInt32(Properties.Settings.Default.oreChiusura);
int minuti = Convert.ToInt32(Properties.Settings.Default.minutiChiusura);
DateTime t1 = DateTime.Now;

if(t1.Hour == ore && t1.Minute ==  minuti)
{
   //Stuff
}

This code compares true values of hours and minutes, instead of their string values.

Paweł Mach
  • 705
  • 1
  • 11
  • 23