azfar
azfar

Reputation: 11

Operator cannot be applied

I'm new in programming. I get the error when writing this line of code :

var time = DateTime.Now.ToShortTimeString().ToString();
var timePattern = "09:30";
            if (time.ToString() <= timePattern.ToString())
{
//disable the button
}

the error display: Operator '<=' cannot be applied to operands of type 'string' and 'string'

Can anybody help me?

Upvotes: 0

Views: 253

Answers (5)

Idle_Mind
Idle_Mind

Reputation: 39122

You can do it without specifying year/month/day...

        if (DateTime.Now.TimeOfDay < new TimeSpan(9, 30, 0))
        {
            // ... it's before 9:30 am ...
        }

Upvotes: 1

Daniel Imms
Daniel Imms

Reputation: 50149

You should be comparing DateTimes directly, not converting them to strings. The <= operator has been implemented for DateTime so it should be as easy as:

var time = DateTime.Now;
var timePattern = new DateTime(time.Year, time.Month, time.Day, 9, 30, 0);
if (time <= timePattern)
{
    //disable the button
}

FYI you cannot use <= for strings, you will need to use string.CompareTo instead.

if (time.ToString().CompareTo(timeParrent.ToString()) <= 0)

Or the static method string.Compare for an alternative syntax.

if (string.Compare(time.ToString(), timeParrent.ToString()) <= 0)

Also DateTime.ToShortTimeString() won't give the format in a sortable (in all cases) format. You can use time.ToString("u") to get the date as a string using the sortable date/time pattern format. An example use case where you would want to do this would be printing the date into HTML and having JavaScript sort it.

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

You can't apply the less than equal (<=) operator to type string.

It looks like you're trying to check if the current time is less than 9:30. To do that, compare DateTime instances.

DateTime currentTime = DateTime.Now;
//Creates a DateTime instance with the current year, month, day at 9:30AM
DateTime nineThirty = 
    new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 9, 30, 0);
if(currentTime.TimeOfDay <= nineThirty.TimeOfDay)
{
    //your code
}

Upvotes: 2

Emond
Emond

Reputation: 50672

Do not turn DateTimes into strings to compare them, use the DateTimes directly.

To turn a string into a DateTime, use DateTime.Parse or DateTime.ParseExact

Note

To compare strings:

Use String.Compare to compare strings like this.

<= hasn't been implemented for strings.

Upvotes: 0

TGH
TGH

Reputation: 39248

The <= operator is not defined for the values of strings. You should instead make your comparisons in terms of DateTime instances

Look at this: http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx

Upvotes: 0

Related Questions