简体   繁体   中英

c#: initialize a DateTime array

I am a bit lost on how to do this. I know how to initialize an array with values at the time of declaration. But how would I do it with a DateTime type array since it takes multiple arguments to create a date?

You mean like this?

DateTime[] dateTimes = new DateTime[]
{
    new DateTime(2010, 10, 1),
    new DateTime(2010, 10, 2),
    // etc
};
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);

If you want to build an array for time span between two dates you could do something like this:

        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;
        }
DateTime [] "name_of_array"=new Date[int lenght_of_the_array]; //this is the array DateTime

然后当您在数组的每个位置分配值时:

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
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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM