62,243
社区成员




string str="2008-1-1,2008-1-4,2008-1-5,2008-1-6,2008-1-7,2008-1-8,2008-1-11,2008-1-15,2008-1-16,2008-1-17,2008-1-25";
string[] arystr=str.Split(',');
string newstr=arystr[0];
for (int i=1;i<arystr.Length;i++)
{
if (Convert.ToDateTime(arystr[i-1]).AddDays(1)==Convert.ToDateTime(arystr[i]))
{
if (Convert.ToDateTime(arystr[i]).AddDays(1)!=Convert.ToDateTime(arystr[i+1])) newstr+="~"+arystr[i];
}
else
newstr+=","+arystr[i];
}
Response.Write(newstr);
static void Main(string[] args)
{
string[] dtstr = new string[] { "2008-1-7","2008-1-15","2008-1-4","2008-1-1", "2008-1-5", "2008-1-6", "2008-1-8", "2008-1-11", "2008-1-16", "2008-1-17", "2008-1-25" };//顺序打乱也可以
DateTime[] dt = Array.ConvertAll<string, DateTime>(dtstr, Convert.ToDateTime);
string str = GetDateTimeString(dt);
Console.WriteLine(str);
}
static string GetDateTimeString(DateTime[] times)
{
string result = string.Empty;
Array.Sort(times);
result += times[0].ToShortDateString();
for (int i = 0; i < times.Length; i++)
{
int index = i;
while (index < times.Length - 1 && times[index] == times[index + 1].AddDays(-1))
index++;
if (index != i)
{
result += "~" + times[index].ToShortDateString();
i = index - 1;
}
else if (index != times.Length - 1)
result += "," + times[i + 1].ToShortDateString();
}
return result;
}
provate string s ()
{
string[] dtstr = new string [] { "2008-1-1", "2008-1-4","2008-1-5","2008-1-6","2008-1-7","2008-1-8","2008-1-11","2008-1-15","2008-1-16","2008-1-17","2008-1-25"};
string result = dtstr[0];
DateTime dts=Convert.ToDateTime(dtstr[0]);
bool b = false ;
for (int i = 1; i < dtstr.Length; i++)
{
DateTime dte = Convert.ToDateTime(dtstr[i]);
if (dts.Subtract(dte).TotalDays == -1 )
{
if (!b)
{
result += "~";
b = true;
}
}
else
{
if (b)
{
result += dtstr[i - 1];
}
result += ","+dtstr[i];
b = false;
}
dts = dte;
}
if (b)
{
result += dtstr[dtstr.Length - 1];
}
return result;
}