也许您想将两个DateTime
参数传递给该方法,那么它更有意义:
public static string DateToString(DateTime dateStart, DateTime dateEnd)
{
if (dateStart.Year == dateEnd.Year && dateStart.Month == dateEnd.Month)
{
return string.Format("{0} - {1}, {2}"
, dateStart.ToString("dd")
, dateEnd.ToString("dd MMMM", CultureInfo.InvariantCulture)
, dateStart.Year);
}
else if (dateStart.Year == dateEnd.Year)
{
return string.Format("{0} - {1}, {2}"
, dateStart.ToString("dd MMMM", CultureInfo.InvariantCulture)
, dateEnd.ToString("dd MMMM", CultureInfo.InvariantCulture)
, dateStart.Year);
}
else
{
return string.Format("{0} - {1}"
, dateStart.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture)
, dateEnd.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture));
}
}
您的样本数据:
var dt1 = new DateTime(2013, 07, 29);
var dt2 = new DateTime(2013, 08, 04);
Console.Write(DateToString(dt1, dt2));
dt1 = new DateTime(2013, 07, 15);
dt2 = new DateTime(2013, 07, 21);
Console.Write(DateToString(dt1, dt2));
输出:
29 July - 04 August, 2013:
15 - 21 July, 2013
因此,根据您的评论,您有一个 DateTime ,您需要先找到一周的开始和结束。然后你想从这两个日期构建字符串:
public static DateTime StartOfWeek(DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
现在您可以使用此方法查找两个日期:
var givenDate = new DateTime(2013, 08, 14);
var startWeekdate = StartOfWeek(givenDate, DayOfWeek.Monday);
var endWeekdate = startWeekdate.AddDays(6);
Console.WriteLine(DateToString(startWeekdate, endWeekdate));
印刷:
12 - 18 August, 2013