簡體   English   中英

c#:初始化一個 DateTime 數組

[英]c#: initialize a DateTime array

我對如何做到這一點有點迷茫。 我知道如何在聲明時用值初始化數組。 但是我將如何使用 DateTime 類型數組來實現,因為它需要多個參數來創建日期?

你的意思是這樣?

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);

如果您想為兩個日期之間的時間跨度構建一個數組,您可以執行以下操作:

        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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM