简体   繁体   中英

Compare month of year enum with datetime month

I have enum:

public enum MonthsOfTheYear
{
    January = 1,
    February = 2,
    March = 4,
    April = 8,
    May = 16,
    June = 32,
    July = 64,
    August = 128,
    September = 256,
    October = 512,
    November = 1024,
    December = 2048,
    AllMonths = 4095,
}  

and Datime.Now.Month.

For example if value of month is 5 it equals "May", how I can compare with the month enum? This example not work: if (!monthsOfYear.Any(x=>x.Code.Equals((MonthsOfTheYear)(1 << (currentDateTime.Month - 1)))

This is a bit of a strange way to represent a month, but it is not difficult to do what you want.

The operator you need is the left bit shift operator , << . If you imagine a number as a string of bits, say

0000 0000 1111 0000  (240 in binary)

then the bit shift operators shift them some number of places to the left or right; shifting left one would be

0000 0001 1110 0000  (480 in binary)

In your case, January is the bit 1 shifted left zero times, February is the bit 1 shifted left one time, and so on:

int may = 5;
MonthsOfTheYear result = (MonthsOfTheYear)(1 << (may - 1));

Make sense?

UPDATE:

What is wrong with this code?

 !monthsOfYear.Any(x=>x.Code.Equals((MonthsOfTheYear)(1 << (currentDateTime.Month - 1))))) 

where monthsOfYear is 1 + 2 + 4 + 8 ?

You have the number 1 + 2 + 4 + 8 which is 15. That is not equal to 1, 2, 4 or 8. You don't want equality in the first place.

To test whether a flag is set, use the & operator.

Let's make this easier to understand by abstracting away into a helper method:

// Is bit "flag" set in bit field "flags"?
static bool IsFlagSet(int flags, int flag)
{
    return (flags & (1 << flag)) != 0;
}

Make sure you understand how that works. If you have flags

0000 0011

And you ask if flag 1 is set then it shifts the bit 1 to the left by 1 place:

0000 0010

And then says "give me 1 if both corresponding bits are set, zero otherwise." So that's

0000 0010

That is not zero, so the flag must have been set.

Now you can say:

bool result = IsFlagSet((int)monthsOfYear, currentDateTime.Month - 1);

This gives you true if that flag was set, false otherwise.

Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM