繁体   English   中英

.years和.months的真实时间跨度对象

[英]A Real Timespan Object With .Years & .Months

请考虑以下两种情况:情况1)。 今天是2012年5月1日,以及方案2)。 今天是2012年9月1日。

现在,考虑一下我们在网页上写了关于某人留下的评论的以下内容:“此评论是在3个月零12天前写的”。 即使陈述完全相同,在这两种情况下的天数总是会有所不同。 在方案1中,“ 3个月12天”等于102 days 但是,在方案2中,“ 3个月12天”将是104 days

现在,让我谈谈我的观点,让我们使用其他示例,并说有人在2013年1月30日对我们的网站发表了评论,今天是2013年3月10日。我们的真实TimeSpan对象需要知道这个相对日期,并且可以计算列出以下内容:

  • 三月有十天
  • 一月有1天(从30日到31日)。
  • 不管有多少天(即使是28天),2月都是一个月。

因此,这意味着总共10天+1天+1个月,翻译成This comment was posted 1 Month and 11 Days agoThis comment was posted 1 Month and 11 Days ago

现在,如果您使用MS样式的TimeSpan对象(或任何语言的任何TimeSpan对象),它将为您提供从1月30日到3月10日的天数(39天),并且因为TimeSpan对象不存储相对日期(我们减去的基本/初始日期以得出TimeSpan),如果您询问它已经过了多少个月和几天,它将假设一个月中有30天,甚至更糟糕的是,平均时间大于30天,然后将剩余的天数返回,因此到39天为止,它将告诉您已经1个月零9天,并且您会收到“ This comment was posted 1 Month and 9 Days ago消息。 请记住,这两种情况都具有相同的开始日期和相同的当前/结束日期,是的,Microsoft TimeSpan对象通过不允许我们告知应该考虑2013年2月,从而为我们提供了完全不同的TimeSpan,整整2天。 实际上,它欺骗了我们。

问题是,人们会相信这一点,并且谁知道他们可能会有什么样的看法,他们对过去的看法可能会如何变化以及在尝试重建自己内心内过去的事件时可能做出的决定和生活选择,而从来没有注意到或理解代表时间的缺点和固有的失败,这种现象在当今的每个地方都如此普遍。 他们不会理解,编程语言没有意识到(或关心)上个月有31天(与30、29或28相反),反之亦然,而当您增加TimeSpan时,这一点就加起来了。

这是这篇文章的核心问题。 我了解到,大多数人不会在意这种差异(但请确保我们中的某些人会这样做,并且不能背对背书),并且如果这不打扰您,那就可以了。 我希望它不会打扰我,我会为自己节省一些时间,压力和失望。 如果这并不麻烦,则可以使用该功能对相对时间进行有效的文本显示(可将其设置为从几秒到数年的1到6个节点),而不必将其用于通常提供的可以忽略的精度。

令我感到失望的是,我没有真正的跨度对象,如果有跨度,并且执行.years.months ,则一无所获,您将只能获得.days或更低的日期,因为timeSpan对象不携带可以告诉它创建timeSpan的哪个月份或年份。 因此,它永远不会真正知道自每个月的天数在一年中变化甚至a年以来已经变化了多少个月。

对此,我将发布一个我开发的函数以获取准确的读数并能够在ASP.NET网页上返回类似以下内容的内容...

发表4年零3个月14天15小时18分钟24秒前

我以为会有一个……

timeSpan.GetActualNumberOf[Months/Days/Hours/etc] (当然必须提供基本日期)

…在此数据类型上键入方法,但没有。

您真正要做的就是在timeSpan对象上创建另一个属性,以为其提供计算差异的基准日期,然后上述可爱的字符串将很容易计算,并且将存在.year.month

更新:我在下面的答案中对我的官方答案和代码的用法详细信息进行了重大扩展和更新,100%工作答案和代码(完整),准确和准确的相对时间/日期,没有近似值-谢谢。

这是使用平均值使用C#为此添加一些扩展方法的方法:

public static class TimeSpanExtensions
{
    public static int GetYears(this TimeSpan timespan)
    {
        return (int)(timespan.Days/365.2425);
    }
    public static int GetMonths(this TimeSpan timespan)
    {
        return (int)(timespan.Days/30.436875);
    }
}

您要找的东西确实不是TimeSpan代表的。 TimeSpan将间隔表示为滴答计数,而不考虑基础DateTimeCalendar

在这里,新的DateDifference类型可能更有意义,因为构造函数或工厂方法采用基本DateTime ,目标DateTime以及可选的Calendar (默认为CultureInfo.CurrentCulture)来计算各种差异分量(年,月等)。 )

编辑:在我看来像野田的时间可能有你需要的工具-的Period类“[R] epresents一段人类时间来表示时间:小时,天,周,月等”,并在特定的Period.Between(then, now, PeriodUnits.AllUnits)似乎是您要的精确计算,但它肯定比TimeSpan复杂得多。 野田时间Wiki上的“ 关键概念”页面介绍了“人类如何使时间变得凌乱”:

撇开天文学和相对论的棘手问题,人类仍然使时间难以谈判。 如果我们都使用Unix时代的记号来谈论时间,那么就不需要Noda Time这样的库了。

但是,不,我们喜欢在数年,数月,数天,数周的时间内进行交谈-出于某种原因,我们喜欢中午12点(令人困惑的是下午1点之前)大约是太阳最高的时间 ...所以我们有时区

不仅如此,我们还没有就多少个月达成共识。 不同的文明提出了不同的分解年份的方法,并且从开始的年份开始使用了不同的数字。 这些是日历系统

这是代码的主要答案,请注意,您可以获得任意数量的日期/时间精度,秒和分钟或秒,分钟和天,最多可达几年(可能包含6个部分/段)。 如果您指定前两个且已超过一年,则它将返回“ 1年零3个月前”,而不会返回其余部分,因为您已请求了两个细分。 如果只使用了几个小时,则只会返回“ 2小时零一分钟前”。 当然,如果您指定1、2、3、4、5或6个segmet,则同样的规则也适用(由于秒,分钟,小时,天,月,年,年仅产生6种类型,因此最大为6)。 它还将纠正语法问题,例如“分钟”与“分钟”,具体取决于是否为1分钟或更长,所有类型均相同,并且生成的“字符串”在语法上始终正确。

以下是一些使用示例:bAllowSegments标识要显示的段数...即:如果为3,则返回字符串为(例如)... "3 years, 2 months and 13 days" (不包括小时,分钟和秒(返回前3个时间类别)),但是,如果日期是较新的日期(例如几天前的日期),则指定相同的细分(3)将返回"4 days, 1 hour and 13 minutes ago" ,因此它将所有因素都考虑在内!

如果bAllowSegments为2,则将返回"3 years and 2 months" ,如果6(最大值)将返回"3 years, 2 months, 13 days, 13 hours, 29 minutes and 9 seconds" ,但是请注意,它将NEVER RETURN "0 years, 0 months, 0 days, 3 hours, 2 minutes and 13 seconds ago"因为它知道前3个细分中没有日期数据,即使您指定了6个细分,也将忽略它们,因此不用担心:)。 当然,如果其中有一个段为0,则在形成字符串时会考虑到这一点,并显示为"3 days and 4 seconds ago""3 days and 4 seconds ago"而忽略了“ 0小时”部分! 享受,如果您愿意,请发表评论。

 Public Function RealTimeUntilNow(ByVal dt As DateTime, Optional ByVal bAllowSegments As Byte = 2) As String
  ' bAllowSegments identifies how many segments to show... ie: if 3, then return string would be (as an example)...
  ' "3 years, 2 months and 13 days" the top 3 time categories are returned, if bAllowSegments is 2 it would return
  ' "3 years and 2 months" and if 6 (maximum value) would return "3 years, 2 months, 13 days, 13 hours, 29 minutes and 9 seconds"
  Dim rYears, rMonths, rDays, rHours, rMinutes, rSeconds As Int16
  Dim dtNow = DateTime.Now
  Dim daysInBaseMonth = Date.DaysInMonth(dt.Year, dt.Month)

  rYears = dtNow.Year - dt.Year
  rMonths = dtNow.Month - dt.Month
  If rMonths < 0 Then rMonths += 12 : rYears -= 1 ' add 1 year to months, and remove 1 year from years.
  rDays = dtNow.Day - dt.Day
  If rDays < 0 Then rDays += daysInBaseMonth : rMonths -= 1
  rHours = dtNow.Hour - dt.Hour
  If rHours < 0 Then rHours += 24 : rDays -= 1
  rMinutes = dtNow.Minute - dt.Minute
  If rMinutes < 0 Then rMinutes += 60 : rHours -= 1
  rSeconds = dtNow.Second - dt.Second
  If rSeconds < 0 Then rSeconds += 60 : rMinutes -= 1

  ' this is the display functionality
  Dim sb As StringBuilder = New StringBuilder()
  Dim iSegmentsAdded As Int16 = 0

  If rYears > 0 Then sb.Append(rYears) : sb.Append(" year" & If(rYears <> 1, "s", "") & ", ") : iSegmentsAdded += 1
  If bAllowSegments = iSegmentsAdded Then GoTo parseAndReturn

  If rMonths > 0 Then sb.AppendFormat(rMonths) : sb.Append(" month" & If(rMonths <> 1, "s", "") & ", ") : iSegmentsAdded += 1
  If bAllowSegments = iSegmentsAdded Then GoTo parseAndReturn

  If rDays > 0 Then sb.Append(rDays) : sb.Append(" day" & If(rDays <> 1, "s", "") & ", ") : iSegmentsAdded += 1
  If bAllowSegments = iSegmentsAdded Then GoTo parseAndReturn

  If rHours > 0 Then sb.Append(rHours) : sb.Append(" hour" & If(rHours <> 1, "s", "") & ", ") : iSegmentsAdded += 1
  If bAllowSegments = iSegmentsAdded Then GoTo parseAndReturn

  If rMinutes > 0 Then sb.Append(rMinutes) : sb.Append(" minute" & If(rMinutes <> 1, "s", "") & ", ") : iSegmentsAdded += 1
  If bAllowSegments = iSegmentsAdded Then GoTo parseAndReturn

  If rSeconds > 0 Then sb.Append(rSeconds) : sb.Append(" second" & If(rSeconds <> 1, "s", "") & "") : iSegmentsAdded += 1

parseAndReturn:

  ' if the string is entirely empty, that means it was just posted so its less than a second ago, and an empty string getting passed will cause an error
  ' so we construct our own meaningful string which will still fit into the "Posted * ago " syntax...

  If sb.ToString = "" Then sb.Append("less than 1 second")

  Return ReplaceLast(sb.ToString.TrimEnd(" ", ",").ToString, ",", " and")

 End Function

当然,您将需要一个“ ReplaceLast”函数,该函数需要一个源字符串,一个参数指定需要替换的内容,另一个arg指定您要替换的内容,并且它仅替换该字符串的最后一次出现...如果您没有一个或不想实现它,我已经包含了我的一个,因此在这里,它可以“按原样”运行而无需修改。 我知道不再需要反向功能(存在于.net中),但是ReplaceLast和ReverseIt函数已从.net之前的日期开始沿用,因此请原谅它看起来过时(仍然可以100%使用, em超过十年,可以保证它们没有错误)... :)。 另外,如果您使用的是VB6,则可以使用StrReverse(将其用.ReverseIt扩展方法扩展的字符串环绕),而不是使用ReverseIt()函数(作为扩展方法提供)。 因此,您不必执行sReplacable.ReverseIt,而是执行StrReverse(sReplacable),因为StrReverse()是VB6内置函数(并且执行完全相同的操作,反转给定的字符串,并且仅执行其他操作)。 如果您使用StrReverse()而不是我的通用ReverseIt函数,请随时删除ReverseIt函数/扩展名。 只要您导入旧版ms-visualbasic-dll库,StrReverse()函数就应该在.NET中可用。 两种方式都没有区别,在我还不知道StrReverse()函数存在之前就已经编写了ReverseIt(),并且自从习惯以来就一直在使用它(没有真正的理由使用我的而不是内置的泛型函数) StrReverse)-实际上,我敢肯定StrReverse(或类似的,较新的.NET特定版本的字符串反向函数)的编写效率更高:)。 干杯。

<Extension()> _ 
Public Function ReplaceLast(ByVal sReplacable As String, ByVal sReplaceWhat As String, ByVal sReplaceWith As String) As String 
    ' let empty string arguments run, incase we dont know if we are sending and empty string or not. 
    sReplacable = sReplacable.ReverseIt 
    sReplacable = Replace(sReplacable, sReplaceWhat.ReverseIt, sReplaceWith.ReverseIt, , 1) ' only does first item on reversed version! 
    Return sReplacable.ReverseIt.ToString 
End Function 

<Extension()> _ 
Public Function ReverseIt(ByVal strS As String, Optional ByVal n As Integer = -1) As String 
    Dim strTempX As String = "", intI As Integer 

    If n > strS.Length Or n = -1 Then n = strS.Length 

    For intI = n To 1 Step -1 
        strTempX = strTempX + Mid(strS, intI, 1) 
    Next intI 

    ReverseIt = strTempX + Right(strS, Len(strS) - n) 

End Function 

好吧,迟到总比我想像中要好;

C#函数提供一切

这是我的修改版本:

private string GetElapsedTime(DateTime from_date, DateTime to_date) {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
int milliseconds;

//------------------
// Handle the years.
//------------------
years = to_date.Year - from_date.Year;

//------------------------
// See if we went too far.
//------------------------
DateTime test_date = from_date.AddMonths(12 * years);

if (test_date > to_date)
{
    years--;
    test_date = from_date.AddMonths(12 * years);
}

//--------------------------------
// Add months until we go too far.
//--------------------------------
months = 0;

while (test_date <= to_date)
{
    months++;
    test_date = from_date.AddMonths(12 * years + months);
}

months--;

//------------------------------------------------------------------
// Subtract to see how many more days, hours, minutes, etc. we need.
//------------------------------------------------------------------
from_date = from_date.AddMonths(12 * years + months);
TimeSpan remainder = to_date - from_date;
days = remainder.Days;
hours = remainder.Hours;
minutes = remainder.Minutes;
seconds = remainder.Seconds;
milliseconds = remainder.Milliseconds;

return (years > 0 ? years.ToString() + " years " : "") +
       (months > 0 ? months.ToString() + " months " : "") +
       (days > 0 ? days.ToString() + " days " : "") +
       (hours > 0 ? hours.ToString() + " hours " : "") +
       (minutes > 0 ? minutes.ToString() + " minutes " : "");}

我要说的是,当前的TimeSpan是一个真实的时间跨度对象,即,2008年1月1日凌晨1:31到2008年2月3日凌晨6:45的时间与2月5日之间的时间是相同的,2008年1月45日和2008年3月9日6:59 pm。 实际上,您要查找的是两个日期时间之间的差异。

至于.MakeMagicHappen.gimmeSomethingPretty.surelyMShasThoughtAboutThisDilema可以满足您系统的特定需求,这就是为什么人们雇用您作为程序员。 如果您使用的框架绝对可以完成所有工作,那么您的公司只需按一个按钮,他们的系统就会完全弹出来,您和我们其他程序员一样会失业。

使用.Net 4.5和CultureInfo类,可以给指定的日期添加月份和年份。

DateTime datetime = DateTime.UtcNow;
int years = 15;
int months = 7;

DateTime yearsAgo = CultureInfo.InvariantCulture.Calendar.AddYears(datetime, -years);
DateTime monthsInFuture = CultureInfo.InvariantCulture.Calendar.AddMonths(datetime, months);

由于要进行大量输入,因此我更喜欢创建扩展方法:

public static DateTime AddYears(this DateTime datetime, int years)
{
    return CultureInfo.InvariantCulture.Calendar.AddYears(datetime, years);
}

public static DateTime AddMonths(this DateTime datetime, int months)
{
    return CultureInfo.InvariantCulture.Calendar.AddMonths(datetime, months);
}

DateTime yearsAgo = datetime.AddYears(-years);
DateTime monthsInFuture = datetime.AddMonths(months);

我相信以下方法是非常可靠和直接的,因为它基于框架日期计算,并返回可读的经过时间字符串,例如Facebook的时间字符串。 对不起葡萄牙语的小字和复数处理,对于我来说是有必要的。

public static string ElapsedTime(DateTime dtEvent)
{
    TimeSpan TS = DateTime.Now - dtEvent;

    int intYears = TS.Days / 365;
    int intMonths = TS.Days / 30;
    int intDays = TS.Days;
    int intHours = TS.Hours;
    int intMinutes = TS.Minutes;
    int intSeconds = TS.Seconds;

    if (intYears > 0) return String.Format("há {0} {1}", intYears, (intYears == 1) ? "ano" : "anos");
    else if (intMonths > 0) return String.Format("há {0} {1}", intMonths, (intMonths == 1) ? "mês" : "meses");
    else if (intDays > 0) return String.Format("há {0} {1}", intDays, (intDays == 1) ? "dia" : "dias");
    else if (intHours > 0) return String.Format("há ± {0} {1}", intHours, (intHours == 1) ? "hora" : "horas");
    else if (intMinutes > 0) return String.Format("há ± {0} {1}", intMinutes, (intMinutes == 1) ? "minuto" : "minutos");
    else if (intSeconds > 0) return String.Format("há ± {0} {1}", intSeconds, (intSeconds == 1) ? "segundo" : "segundos");
    else
    {
        return String.Format("em {0} às {1}", dtEvent.ToShortDateString(), dtEvent.ToShortTimeString());
    }
}

我接受了可接受的答案,并将其从VB.Net转换为C#,并进行了一些修改/改进。 我摆脱了用于替换字符串最后一个实例的字符串反转,并使用了一种更直接地查找和替换字符串最后一个实例的扩展方法。

如何调用方法的示例:

PeriodBetween(#2/28/2011#, DateTime.UtcNow, 6)

主要方法:

public static string PeriodBetween(DateTime then, DateTime now, byte numberOfPeriodUnits = 2)
{
    // Translated from VB.Net to C# from: https://stackoverflow.com/a/1956265

    // numberOfPeriodUnits identifies how many time period units to show.
    // If numberOfPeriodUnits = 3, function would return:
    //      "3 years, 2 months and 13 days"
    // If numberOfPeriodUnits = 2, function would return:
    //      "3 years and 2 months"
    // If numberOfPeriodUnits = 6, (maximum value), function would return:
    //      "3 years, 2 months, 13 days, 13 hours, 29 minutes and 9 seconds"

    if (numberOfPeriodUnits > 6 || numberOfPeriodUnits < 1)
    {
        throw new ArgumentOutOfRangeException($"Parameter [{nameof(numberOfPeriodUnits)}] is out of bounds. Valid range is 1 to 6.");
    }

    short Years = 0;
    short Months = 0;
    short Days = 0;
    short Hours = 0;
    short Minutes = 0;
    short Seconds = 0;
    short DaysInBaseMonth = (short)(DateTime.DaysInMonth(then.Year, then.Month));

    Years = (short)(now.Year - then.Year);

    Months = (short)(now.Month - then.Month);
    if (Months < 0)
    {
        Months += 12;
        Years--; // add 1 year to months, and remove 1 year from years.
    }

    Days = (short)(now.Day - then.Day);
    if (Days < 0)
    {
        Days += DaysInBaseMonth;
        Months--;
    }

    Hours = (short)(now.Hour - then.Hour);
    if (Hours < 0)
    {
        Hours += 24;
        Days--;
    }

    Minutes = (short)(now.Minute - then.Minute);
    if (Minutes < 0)
    {
        Minutes += 60;
        Hours--;
    }

    Seconds = (short)(now.Second - then.Second);
    if (Seconds < 0)
    {
        Seconds += 60;
        Minutes--;
    }

    // This is the display functionality.
    StringBuilder TimePeriod = new StringBuilder();
    short NumberOfPeriodUnitsAdded = 0;

    if (Years > 0)
    {
        TimePeriod.Append(Years);
        TimePeriod.Append(" year" + (Years != 1 ? "s" : "") + ", ");
        NumberOfPeriodUnitsAdded++;
    }

    if (numberOfPeriodUnits == NumberOfPeriodUnitsAdded)
    {
        goto ParseAndReturn;
    }

    if (Months > 0)
    {
        TimePeriod.AppendFormat(Months.ToString());
        TimePeriod.Append(" month" + (Months != 1 ? "s" : "") + ", ");
        NumberOfPeriodUnitsAdded++;
    }

    if (numberOfPeriodUnits == NumberOfPeriodUnitsAdded)
    {
        goto ParseAndReturn;
    }

    if (Days > 0)
    {
        TimePeriod.Append(Days);
        TimePeriod.Append(" day" + (Days != 1 ? "s" : "") + ", ");
        NumberOfPeriodUnitsAdded++;
    }

    if (numberOfPeriodUnits == NumberOfPeriodUnitsAdded)
    {
        goto ParseAndReturn;
    }

    if (Hours > 0)
    {
        TimePeriod.Append(Hours);
        TimePeriod.Append(" hour" + (Hours != 1 ? "s" : "") + ", ");
        NumberOfPeriodUnitsAdded++;
    }

    if (numberOfPeriodUnits == NumberOfPeriodUnitsAdded)
    {
        goto ParseAndReturn;
    }

    if (Minutes > 0)
    {
        TimePeriod.Append(Minutes);
        TimePeriod.Append(" minute" + (Minutes != 1 ? "s" : "") + ", ");
        NumberOfPeriodUnitsAdded++;
    }

    if (numberOfPeriodUnits == NumberOfPeriodUnitsAdded)
    {
        goto ParseAndReturn;
    }

    if (Seconds > 0)
    {
        TimePeriod.Append(Seconds);
        TimePeriod.Append(" second" + (Seconds != 1 ? "s" : "") + "");
        NumberOfPeriodUnitsAdded++;
    }

    ParseAndReturn:
    // If the string is empty, that means the datetime is less than a second in the past.
    // An empty string being passed will cause an error, so we construct our own meaningful
    // string which will still fit into the "Posted * ago " syntax.

    if (TimePeriod.ToString() == "")
    {
        TimePeriod.Append("less than 1 second");
    }

    return TimePeriod.ToString().TrimEnd(' ', ',').ToString().ReplaceLast(",", " and");
}

ReplaceLast扩展方法:

public static string ReplaceLast(this string source, string search, string replace)
{
    int pos = source.LastIndexOf(search);

    if (pos == -1)
    {
        return source;
    }

    return source.Remove(pos, search.Length).Insert(pos, replace);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM