开发者

c#: initialize a DateTime array

开发者 https://www.devze.com 2023-01-20 17:13 出处:网络
I am a bit lost on how to do 开发者_StackOverflow社区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 mul

I am a bit lost on how to do 开发者_StackOverflow社区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;
        }


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
}


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

And then when you assign the value in each position of the array:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号