Create a table with dates [closed]

4

I'm creating a table and need the columns to be created as follows: Mon, 23 Nov | Tue, 24 Nov | Wed, 25 Nov | Thu, 26 Nov | Fri, 27 Nov | Sat, 28 Nov | Sun, 29 Nov

To create the table I pass by a date parameter (which is selected through a calendar)

I'm doing this to create the Table:

    DateTime diaAgenda = 'Data que foi selecionada no calendario';

    public DataTable gerarAgenda(DateTime dia)
    {
        DataTable tabela = new DataTable();

        string diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);

        tabela.Columns.Add("" + diahoje);

        for (int data = 1; data < 7; data++)
        {
            dia = dia.AddDays(1);
            diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);
            tabela.Columns.Add("" + diahoje);
        }
        return tabela;            
    }

In this way, the table that I generate will have the following columns:

Thu, 26 Nov | Fri, 27 Nov | Sat, 28 Nov | Sun, 29 Nov | Mon, 30 Nov | Tue, Dec 01 | Wed, Dec 02 |

How could I do to create the columns like this:

Mon, 23 Nov | Tue, 24 Nov | Wed, 25 Nov | Thu, 26 Nov | Fri, 27 Nov | Sat, 28 Nov | Sun, 29 Nov

    
asked by anonymous 26.11.2015 / 17:30

3 answers

4

If I understood your problem then I would say it is simply the% cos_de% parameter you are passing. You are not passing it by marking a Monday, so the "error" does not start on the second as you wish.

public DataTable gerarAgenda(DateTime dia)
{
    switch(dia.DayOfWeek)
    {
        case DayOfWeek.Tuesday: dia.AddDays(-1); break;
        case DayOfWeek.Wednesday: dia.AddDays(-2); break;
        case DayOfWeek.Thursday: dia.AddDays(-3); break;
        case DayOfWeek.Friday: dia.AddDays(-4); break;
        case DayOfWeek.Saturday: dia.AddDays(-5); break;
        case DayOfWeek.Sunday: dia.AddDays(-6); break;
    }

    DataTable tabela = new DataTable();

    string diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);

    tabela.Columns.Add("" + diahoje);

    for (int data = 1; data < 7; data++)
    {
        dia = dia.AddDays(1);
        diahoje = String.Format("{0:ddd, MMM d, yyyy}", dia);
        tabela.Columns.Add("" + diahoje);
    }
    return tabela;            
}
    
26.11.2015 / 17:54
2

You can check if it's Monday like that ..

if(dia == DayOfWeek.Saturday)
    
26.11.2015 / 18:04
2

Ah! You want the first column to be MONDAY, is that it? Test there:

var diaDaSemana = (int) dia.DayOfWeek;
var inicioDaSemana = dia.AddDays(diaDaSemana-1);
for (int dias = 1; dias < 7; dias++)
{
    data = inicioDaSemana.AddDays(dias);
    dataFormatada = String.Format("{0:ddd, MMM d, yyyy}", data);
    tabela.Columns.Add("" + dataFormatada);
}

But taking advantage of the cue, it seems very unproductive - or even inadequate - what you are trying to do.

I recommend giving this code a refactor. It is very strange the final result of it.

    
26.11.2015 / 19:42