我正在寻找一个可以输入2个日期的函数:
从这样开始:
public static String getDaysOrWeeksFromDateDiff(DateTime first, DateTime second)
{
//this function will substract the date from the other and result days if < 8 and weeks if > 7
return "1 week";
}
我在下面尝试过这个功能,但它给了我一个负面日期(我在计算中错过了一年)
public static String getDaysOrWeeksFromDateDiff(DateTime first, DateTime second)
{
var cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
var weeknr = cal.GetWeekOfYear(first, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
var weeknr2 = cal.GetWeekOfYear(second, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
String strReturnValue;
if (weeknr == weeknr2)
{
var dagen = first.Day - second.Day;
strReturnValue = (dagen == 0 ? "today" : (dagen == 1 ? "1 day" : dagen + " days"));
}
else
{
strReturnValue = (weeknr - weeknr2 == 1 ? "1 week" : weeknr - weeknr2 + " weeks");
}
return strReturnValue;
}
答案 0 :(得分:5)
TimeSpan difference = second - first;
这会返回TimeSpan object,您可以轻松查询,例如
if (difference.Days >= 8) ...
将Days
的数量转换为数周应该是一项微不足道的练习,因为每周都有7天......
答案 1 :(得分:2)
您可以使用时间跨度类
public static String getWeekOrMonthFromDateDiff(DateTime first, DateTime second)
{
var span = second - first;
if (span.Days <= 7)
return span.Days + " day(s)";
else
return span.Days / 7 + " week(s)";
}
答案 2 :(得分:1)
你可以简单地做
TimeSpan diff = first - second;
然后你可以做
int weekCount = diff.TotalDays / 7;
答案 3 :(得分:1)
我几天前做过这样的事情:
private string GetTimeSpan(DateTime toDateTime, DateTime fromDateTime)
{
TimeSpan ts = toDateTime- fromDateTime;
if (ts.Days < 0)
{
return "since " + ts.Days.ToString().Replace("-", string.Empty) + " Days";
}
else if (ts.Hours < 1)
{
return "in " + ts.Minutes + " Minutes";
}
else if (ts.Days < 1)
{
return "in " + ts.Hours + " Hours";
}
else if (ts.Days < 7)
{
return "in " + ts.Days + " Days";
}
else
{
return "in " + ts.Days / 7 + " Weeks";
}
}
按照您需要的方式修改它:)
答案 4 :(得分:1)
在这样的时间长度内,您应该使用TimeSpan
代替DateTime
,然后从属性TotalDays
计算周数。
答案 5 :(得分:-1)
void func(DateTime t1, DateTime t2)
{
days = (t2 - t1).TotalDays;
weeks = days/7;
year = weeks/52;
}