-2

I'm attempting to write my first C# script. The script is for opening hours... My if ((weekDay == sunday) && time > openingTime && closingTime < time) line is spitting errors due to:

CS0019 C# Operator '<' cannot be applied to operands of type 'string' and 'int'

After looking at related answers on SO, I still haven't been able to get my code working. I've tried converting the string into an int, this didn't work (unless I did something stupid)

var weekDay = DateTime.Today.DayOfWeek;
var isOpen = "We are open!";
var isClosed = "We are closed";
var sunday = DayOfWeek.Sunday;


var time = DateTime.Now.ToString("hh:mm");

var openingTime = 08;
var closingTime = 16;


if ((weekDay == sunday) && time > openingTime && time < closingTime)
{
    Console.WriteLine(isClosed);
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Duke Dodson
  • 86
  • 1
  • 1
  • 8
  • Your `time` variable is of type `string` - you cannot compare a `string` to an `int` (which both `openingTime` and `clostingTime` are). – Preston Guillot Feb 03 '19 at 19:03

2 Answers2

2

You can use DateTime struct insted of string and use its properties like Hour to retrieve current hour.

var time = DateTime.Now;
if ((time.DayOfWeek == sunday) && time.Hour > openingTime && closingTime < time.Hour)
{
    Console.WriteLine(isClosed);
}

This is a more structured way to solve a problem then convert DateTime to string and then parse the string back to extract current hour.

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
1

It seems that you want to evaluate against the current hour. Use the DateTime.Hour property instead, you cannot do the comparison between an int and a string.

var weekDay = DateTime.Today.DayOfWeek;
var isOpen = "We are open!";
var isClosed = "We are closed";
var sunday = DayOfWeek.Sunday;


var time = DateTime.Now.Hour;

var openingTime = 8;
var closingTime = 16;


if ((weekDay == sunday) && time > openingTime && time < closingTime)
{
    Console.WriteLine(isClosed);
}
yv989c
  • 1,453
  • 1
  • 14
  • 20