modest and cute girl
modest and cute girl

Reputation: 785

c# months and years between given dates

I try to popup a msgbox that shows the months and years of the given dates for example my input is:

7/2012 and 2/2013

and the output should be:

7/2012,8/2012,9/2012,10/2012,11/2012,12/2012,1/2013,2/2013

I wrote:

    string datePart1;
    string datePart2;
    string[] date1 = new string[] { "" };
    string[] date2 = new string[] { "" };

    private void button1_Click(object sender, EventArgs e)
    {
        DateTime endDate = new DateTime(2013, 2, 1);  // i will be having the date time as a variable from a textbox
        DateTime begDate = new DateTime(2012, 7, 1);  // i will be having the date time as a variable from a text box

        int year, month;

        if (endDate.Month - begDate.Month < 0)
        {
            month = (endDate.Month - begDate.Month) + 12;
            endDate = new DateTime(endDate.Year - 1, endDate.Month, endDate.Day);
        }
        else
            month = endDate.Month - begDate.Month;

        year = endDate.Year - begDate.Year;

The above code calculates the time difference, but my attempts at outputting haven't worked.

Upvotes: 2

Views: 3180

Answers (4)

Matthew Watson
Matthew Watson

Reputation: 109567

Here's a sample to get you started.

It provides a handy MonthsInRange() method which returns a sequence of all the months in the specified range. You can then format the returned dates using "M\\/yyyy" (see below) to output the required format. (Note: That's not a letter V, it's a backslash followed by a forward slash!)

See Custom Date and Time Format Strings for an explanation of the format string.

using System;
using System.Collections.Generic;

namespace Demo
{
    public static class Program
    {
        static void Main(string[] args)
        {
            DateTime endDate = new DateTime(2013, 2, 1);
            DateTime begDate = new DateTime(2012, 7, 1);

            foreach (DateTime date in MonthsInRange(begDate, endDate))
            {
                Console.WriteLine(date.ToString("M\\/yyyy"));
            }
        }

        public static IEnumerable<DateTime> MonthsInRange(DateTime start, DateTime end)
        {
            for (DateTime date = start; date <= end; date = date.AddMonths(1))
            {
                yield return date;
            }
        }
    }
}

Why "M\\/yyyy" and not just "M/yyyy"?

This is because the "/" character in a DateTime format string will be interpreted as the "date separator", not a literal "/". In some locales, this will come out as "." and not "/".

To fix this, we need to escape it with a "\" character. However, we can't just use a single "\" because C# itself will interpret that as an escape character, and will use it to escape the following character. The C# escape sequence for a literal "\" is "\\", which is why we have to put "\\/" and not just "\/".

Alternatively you can turn of escaping of "\" characters by prefixing the string with an @ character, like so:

@"M/yyyy"

You can use whichever you prefer.

Upvotes: 3

Austin Salonen
Austin Salonen

Reputation: 50225

Since you're not guaranteed to have dates with the same day, you can use this code which creates new dates that only consider the first of the month.

static IEnumerable<string> InclusiveMonths(DateTime start, DateTime end)
{
    // copies to ensure the same day.
    var startMonth = new DateTime(start.Year, start.Month, 1);
    var endMonth = new DateTime(end.Year, end.Month, 1);

    for (var current = startMonth; current <= endMonth; current = current.AddMonths(1))
        yield return current.ToString("M/yyyy");
}

// usage
foreach (var mmyyyy in InclusiveMonths(begDate, endDate))
{
    Console.WriteLine(mmyyyy);
}

var allMonths = string.Join(", ", InclusiveMonths(begDate, endDate));

Upvotes: 2

Nolonar
Nolonar

Reputation: 6122

You may use

TimeSpan dateDifference = endDate - begDate;
year = dateDifference.Days / 365;
month = dateDifference.Days / 30;

Edit: I forgot TimeSpan does not feature Year or Month, sorry :(

Upvotes: 0

Steve Stokes
Steve Stokes

Reputation: 1230

Look into using the TimeSpan structure, it'll help you achieve your goal a lot faster.

http://msdn.microsoft.com/en-us/library/system.timespan.aspx

Upvotes: 0

Related Questions