我正在寻找一个可以输入 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;
}
您可以直接减去日期:
TimeSpan difference = second - first;
这将返回一个 TimeSpan 对象,您可以轻松查询该对象,例如
if (difference.Days >= 8) ...
将Days
数转换为周数应该是一项微不足道的练习,因为每周正好有 7 天......
(请注意,Days
将以整数形式提供天数,而TotalDays
将包括小数天数。
您可以使用时间
跨度类
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)";
}
你可以
简单地做
TimeSpan diff = first - second;
然后你可以做
int weekCount = diff.TotalDays / 7;
几天前我做了这样的事情:
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";
}
}
按照您需要的方式修改它:)
对于这样的时间长度,您应该使用TimeSpan
而不是DateTime
,然后从属性TotalDays
计算周数。
void func(DateTime t1, DateTime t2)
{
days = (t2 - t1).TotalDays;
weeks = days/7;
year = weeks/52;
}