In VB6 code, I have the following:
dim I as Long
I = Weekday(Now, vbFriday)
I want the equivalent in C#. Can any one help?
public static int Weekday(DateTime dt, DayOfWeek startOfWeek)
{
return (dt.DayOfWeek - startOfWeek + 7) % 7;
}
This can be called using:
DateTime dt = DateTime.Now;
Console.WriteLine(Weekday(dt, DayOfWeek.Friday));
The above outputs:
4
as Tuesday is 4 days after Friday.
You mean the DateTime.DayOfWeek property?
DayOfWeek dow = DateTime.Now.DayOfWeek;
Yes, Each DateTime value has a built in property called DayOfWeek that returns a enumeration of the same name...
DayOfWeek dow = DateTime.Now.DayOfWeek;
If you want the integral value just cast the enumeration value to an int.
int dow = (int)(DateTime.Now.DayOfWeek);
You'll have to add a constant from 1 to 6 and do Mod 7 to realign it to another day besides Sunday, however...
I don't think there is an equivalent of the two argument form of VB's Weekday function.
You could emulate it using something like this;
private static int Weekday(DateTime date, DayOfWeek startDay)
{
int diff;
DayOfWeek dow = date.DayOfWeek;
diff = dow - startDay;
if (diff < 0)
{
diff += 7;
}
return diff;
}
Then calling it like so:
int i = Weekday(DateTime.Now, DayOfWeek.Friday);
It returns 4 for today, as Tuesday is 4 days after Friday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With