Untitled Document
Login :: Register :: Site RSS Feed      
Untitled-1
Blogs
Untitled-1
Archives
Untitled-1
Search...
Free Counter and Web Stats
Untitled-1
C# DayOfWeek as numeric
Location: BlogsBean LabsProgramming (C#/.Net/etc)    
Posted by: frijoles 3/1/2007
I'm writing a timecard program for our workplace. I was trying to get the day of the week as a number (today being Friday, I was looking for a '5'). I couldn't find much info on Google, aside from some article talking about something unrelated. I saw a snippit of code there. Too easy, I thought:

    int dayofweek  = (int)DateTime.Now.DayOfWeek;

And that's it. *slaps forehead* I suppose I should have tried that first since it's a two-second check. Oh well. Since I was searching Google without much luck, I hope to get this out there so others might see it.

As for finding a specific day of the week, I went with this for now:

    int dayofweek = (int)DateTime.Now.DayOfWeek;
    int offset = 0;
    DateTime thisFriday;

    if (dayofweek < 5)
        offset = 5 - dayofweek;
    else
        offset = dayofweek - 5;

    thisFriday = DateTime.Now.AddDays(offset);


I spent about 5 minutes doing that. It calculates when the next upcoming Friday is (if the current date is Friday, then it shows that). I've set it in to a for loop to spit out a month of Fridays by combining it with AddDays. As always, let me know if there's a better way.
Permalink |  Trackback

Comments (3)   Add Comment
Re: C# DayOfWeek as numeric    By Greg on 4/18/2008
Error: Cannot implicitly convert type 'int' to 'System.DayOfWeek'. An explicit conversion exists (are you missing a cast?)

Re: C# DayOfWeek as numeric    By Silvos on 7/3/2008
Checkout Enum.Parse... for the other direction

Re: C# DayOfWeek as numeric    By Nascom Snc on 8/29/2008
I resolve with

(Int32)Enum.Parse(typeof(DayOfWeek), dpartenza.DayOfWeek.ToString())



Your name:
Title:
Comment:
Add Comment   Cancel 
Copyright 2006 by mscorlib.com