c#:初始化日期时间数组
我有点不知道怎么做。我知道如何在声明时用值初始化数组。但是,既然DateTime类型数组需要多个参数来创建一个日期,我该如何使用它呢c#:初始化日期时间数组,c#,arrays,datetime,initialization,C#,Arrays,Datetime,Initialization,我有点不知道怎么做。我知道如何在声明时用值初始化数组。但是,既然DateTime类型数组需要多个参数来创建一个日期,我该如何使用它呢 DateTime[] dateTimes = new DateTime[] { new DateTime(2010, 10, 1), new DateTime(2010, 10, 2), // etc }; 然后在数组的每个位置指定值时: DateTime "name_of_each_element_of_the_array"= new
DateTime[] dateTimes = new DateTime[]
{
new DateTime(2010, 10, 1),
new DateTime(2010, 10, 2),
// etc
};
然后在数组的每个位置指定值时:
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
例如,我想添加一个包含4个元素的DateTime数组:DateTime[]myarray=newdatetime[4]//数组已创建
整数年、月、日//创建日期变量
对于(int i=0;i如果要为两个日期之间的时间跨度构建数组,可以执行以下操作:
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;
}
timeEndDate=timeStartDate.AddYears(1);//或.AddMonts等。。
rangeTimeSpan=timeEndDate.Subtract(timeStartDate);//之前声明为TimeSpan对象
rangeTimeArray=new DateTime[rangeTimeSpan.Days];//之前声明为DateTime[]
对于(int i=0;i
看起来很简单。使用new关键字不会导致问题吗?不记得dateTimes是一个DateTime对象数组,所以它里面必须是DateTime类的实例。好的,我没有使用new关键字就尝试过了。似乎只使用{DateTime(x,x,x)}就可以了等等。我只是担心new关键字会为每个值创建新对象,而我并不需要。谢谢!我很困惑。如果你想要一个DateTime对象数组,那么数组中的每个项都应该是新的(或现有的)DateTime对象。当时我还是OOP新手。我完全理解现在发生的事情。lol。最后一行将导致错误,因为数组中只有5个元素。这在声明时不会初始化。
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
}
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;
}