我有 2 种日期时间格式作为出发日期和到达日期,例如 25/04/2014 作为出发和 22/04/2014 作为到达,现在我希望返回这两者之间的日期如下: 22/04/2014|23/04/2014|24/04/2014|25/04/2014 在 C# 中,您对此有任何想法吗?
您可以避免使用 Linq 键入循环
StringBuilder sb = new StringBuilder();
DateTime arrival = new DateTime(2014,4,22);
DateTime departure = new DateTime(2014,4,25);
int days = Convert.ToInt32((departure - arrival).TotalDays);
var rng = Enumerable.Range(0,days+1).ToList();
rng.ForEach(r => sb.Append(arrival.AddDays(r).ToShortDateString() + "|"));
sb.Length--;
Console.WriteLine(sb.ToString());
var startDate = new DateTime(2014, 4, 22);
var endDate = new DateTime(2014, 4, 25);
var sb = new StringBuilder();
while (startDate <= endDate)
{
sb.AppendFormat("|{0}", startDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
startDate = startDate.AddDays(1);
}
Console.WriteLine(sb.ToString().Substring(1));
查看实际效果
喜欢:
var startDate = new DateTime(2014, 04, 25);
var endDate = new DateTime(2014, 04, 29);
var currentDate = startDate;
while (currentDate <= endDate)
{
Console.WriteLine(currentDate);
currentDate = currentDate.AddDays(1);
}
。但格式正确,但这将是视图逻辑。
瞧:
DateTime start = new DateTime(2014, 4, 24);
DateTime end = new DateTime(2014, 4, 22);
DateTime current = start < end ? start : end;
DateTime stop = start < end ? end : start;
List<DateTime> dates = new List<DateTime>();
while (current <= stop)
{
dates.Add(current);
current = current.AddDays(1);
}
StringBuilder sb = new StringBuilder();
foreach (DateTime dt in dates)
{
if (sb.Length > 0)
sb.Append("|");
sb.Append(dt.ToString("dd/MM/yyyy"));
}
Console.WriteLine(sb.ToString());