Solved

How to calculate which day of month a given day is.

Posted on 2015-01-20
16
52 Views
Last Modified: 2015-01-27
Hi All

Not a very good title, but what I need is to calculate out the interval and week day of any given date.

ie today is the 3rd Tuesday.

Need to do this in ASP.net V4

Andy
0
Comment
Question by:Andy Green
  • 4
  • 4
  • 4
  • +2
16 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 450 total points
ID: 40559484
Try:
DateTime today = DateTime.Today;

DayOfWeek day = today.DayOfWeek;
int interval = (today.Day / 7) + 1;

string suffix = "th";
if (interval == 1) 
    suffix = "st";
else if (interval == 2)
    suffix = "nd";
else if (interval == 3)
    suffix = "rd";

Console.Write("Today is the {0}{1} {2} of the month",
    interval,
    suffix,
     Enum.GetName(typeof(DayOfWeek), day)
);

Open in new window

0
 
LVL 11

Assisted Solution

by:louisfr
louisfr earned 50 total points
ID: 40559511
Just a little correction:
int interval = (today.Day - 1) / 7 + 1;

Open in new window

January 7th was the first Wednesday, not the second.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40559516
Good spot :)
0
 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
ID: 40559523
same idea but different
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication34
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Today;

            DayOfWeek day = today.DayOfWeek;
            int interval = (today.Day - 1) / 7 + 1;
            string suffix;
            switch (interval)
                {
                case 1:
                    suffix = "th";
                    break;
                case 2:
                    suffix = "st";
                    break;
                case 3:
                    suffix = "rd";
                    break;
                default:
                    suffix = "th";
                    break;
                }
            Console.WriteLine("Today is the {0}{1} {2} of the month", interval,suffix,Enum.GetName(typeof(DayOfWeek), day));
                 Console.ReadLine();                                         
        }
    }
}

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40559542
I did think about putting a switch in there, but it didn't seem worth it for 3 values.  I also toyed with an extension method, which for repeated use would be handy, but a bit overkill for a quick example.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 40560024
I like those answers.  Here's a mindless approach that simply iterates backwards to the 1st of the month and counts the number of days that match the one passed in:
        public string DayInterval(DateTime dt)
        {
            int count = 1;
            DayOfWeek day = dt.DayOfWeek;
            while(dt.Day != 1)
            {
                dt = dt.AddDays(-1);
                if (dt.DayOfWeek == day)
                {
                    count++;
                }
            }
            string[] suffix = { "", "st", "nd", "rd", "th", "th" };
            return count.ToString() + suffix[count] + " " + day.ToString();
        }

Open in new window

0
 
LVL 11

Expert Comment

by:louisfr
ID: 40560045
Mindless indeed. I think I once used LINQ for this kind of computation, as a proof of concept.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 40560089
Here's one with ~slightly~ more thought put into it...but still without doing a straight calculation.  More coffee is required before I can do more "complex" math.  ;)
        private string[] suffix = {"st", "nd", "rd", "th", "th" };

        public string DayInterval(DateTime dt)
        {
            int count = 1;
            while(dt.Day > 7)
            {
                count++;
                dt = dt.AddDays(-7);
            }
            return count.ToString() + suffix[count - 1] + " " + dt.DayOfWeek.ToString();
        }

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 11

Expert Comment

by:louisfr
ID: 40560114
Is this a challenge?
public string DayInterval(DateTime dt)
{
    var days = from d in Enumerable.Range(1, dt.Day)
            where new DateTime(dt.Year, dt.Month, d).DayOfWeek == dt.DayOfWeek
            select d;
    return days.Count() + suffix[count - 1] + " " + dt.DayOfWeek;
}

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 40560154
I Love It!  Some great answers in here now (and some not so great; *mine).  Does this mean we have to go back to "real" work now?
0
 
LVL 3

Author Comment

by:Andy Green
ID: 40562188
Thanks guys, Carl I have integrates yours into my code and it fails sometimes, ie it says that the 23 feb 2015 is the 3rd Monday, where it is the 4th.

I'll continue with the other solutions.

Andy
0
 
LVL 3

Author Comment

by:Andy Green
ID: 40562196
Actually ignore that - I had removed the +1 for debugging. I'll post some other discrepancies in a bit.

Andy
0
 
LVL 3

Author Comment

by:Andy Green
ID: 40562205
Not detecting Sundays at all
17 Feb is 3rd Tues with is correct but the 18 is the 4th Wed 19 is 4th Thurs 20 is 4th Fri which are all wrong.

Here is my code have I used it correctly?

                Dim today As DateTime = CType(rtpSlotStart.SelectedDate, DateTime)
                Dim day As DayOfWeek = today.DayOfWeek - 1
                Dim interval As Integer = ((today.Day) / 7) + 1

                ddlMonthDayInterval.SelectedValue = interval
                ddlMonthDay.SelectedValue = Weekday(rtpSlotStart.SelectedDate) - 1 (used as my days start at 0 not 1)

ANdy
0
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 450 total points
ID: 40562261
Looks like i missed the offset. This line:
int interval = (today.Day / 7) + 1;

Open in new window

Should be:
int interval = ((today.Day-1) / 7) + 1;

Open in new window

Which gives:
Output
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40562304
The code Carl provided uses integer divisions.
Your VB code uses floating-point divisions and rounds the result.
Use the integer division operator (and subtract 1 because days start at 1):
Dim interval As Integer = (today.Day - 1) \ 7 + 1

Open in new window

0
 
LVL 3

Author Closing Comment

by:Andy Green
ID: 40572496
Thank guys, sorry I give point all round. to be fair I have used Carls first solution.

Andy
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now