2010-10-22 25 views
8

Hola chicos, estoy un poco perdido en cómo hacer esto. Sé cómo inicializar una matriz con valores en el momento de la declaración, pero ¿cómo lo haría con una matriz de tipo DateTime, ya que se necesitan varios argumentos para crear una fecha?C#: inicializar una matriz DateTime

Respuesta

32

¿Te refieres a esto?

DateTime[] dateTimes = new DateTime[] 
{ 
    new DateTime(2010, 10, 1), 
    new DateTime(2010, 10, 2), 
    // etc 
}; 
+0

Eso parece bastante simple. ¿Usar la nueva palabra clave no va a causar problemas? – Sinaesthetic

+0

No se olvide de dateTimes es una matriz de objetos DateTime por lo que dentro debe ser instancia de la clase DateTime. – Necronet

+0

bien, lo intenté sin la nueva palabra clave. Parece funcionar bien solo con {DateTime (x, x, x)}, etc. Estaba preocupado de que la palabra clave nueva creara objetos nuevos para cada valor, que no necesitaba. ¡Gracias! – Sinaesthetic

5
DateTime [] startDate = new DateTime[5]; 
     startDate[0] = new DateTime(11, 11, 10); 
     startDate[1] = new DateTime(11, 11, 10); 
     startDate[2] = new DateTime(11, 11, 10); 
     startDate[3] = new DateTime(11, 11, 10); 
     startDate[4] = new DateTime(11, 11, 10); 
+2

La última línea causará un error, ya que solo hay 5 elementos en la matriz. – Matt

0
DateTime [] "name_of_array"=new Date[int lenght_of_the_array]; //this is the array DateTime 

Y luego, cuando se asigna el valor en cada posición de la matriz:

DateTime "name_of_each_element_of_the_array"= new DateTime(int value_of_year,int value_of_month, int value_of_day);//this is each element that is added in each position of the array 
0
For example, i want to add a DateTime array of 4 elements:      DateTime[] myarray=new DateTime [4]; //the array is created 
int year, month, day;    //variables of date are created    
for(int i=0; i<myarray.length;i++) 
{ 
    Console.WriteLine("Day"); 
    day=Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("Month"); 
    month=Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("Year"); 
    year=Convert.ToInt32(Console.ReadLine()); 

    DateTime date =new DateTime(year,month,day); //here is created the object DateTime, that contains day, month and year of a date 

myarray[i]=date; //and then we set each date in each position of the array 
} 
+0

Esto no se inicializa a _time of declaration_. – namezero

1

Si usted quiere construir una matriz para un intervalo de tiempo entre dos fechas usted podría hacer algo como esto:

 timeEndDate = timeStartDate.AddYears(1); // or .AddMonts etc.. 
     rangeTimeSpan = timeEndDate.Subtract(timeStartDate); //declared prior as TimeSpan object 
     rangeTimeArray = new DateTime[rangeTimeSpan.Days]; //declared prior as DateTime[] 

     for (int i = 0; i < rangeTimeSpan.Days; i++) 
     { 
      timeStartDate = timeStartDate.AddDays(1); 
      rangeTimeArray[i] = timeStartDate; 
     } 
Cuestiones relacionadas