【问题标题】:Sort error - dates in Unity排序错误 - Unity 中的日期
【发布时间】:2017-07-06 22:58:01
【问题描述】:

这是一个有趣的问题。我正在使用 iComparable 界面按日期对列表进行排序。我今天再次测试它,当我注意到一些东西时。我输入了 2016 年 11 月 1 日作为日期。当数据被发送到屏幕时,该日期是第一个,即使列表中的其他日期在它之前。我意识到系统会认为 11 可能需要位于列表顶部,但我该如何解决这个问题?

public class SortbyDate :IComparer<OilChange> {
  public int Compare(OilChange x, OilChange y) {
    return x.ServiceDate.CompareTo (y.ServiceDate);
  }
}

谢谢!

【问题讨论】:

  • 奇怪。 “OilChange.ServiceDate”属性的类型是什么?真的是 DateTime 还是字符串?
  • 它是一个字符串。 DateTime 的问题太多了。
  • 嗯,这就是排序问题的原因。您在使用 DateTime 时遇到了什么问题?
  • 我无法消除时间部分。

标签: c# list sorting unity3d


【解决方案1】:

我真的建议将字符串变量的类型更改为 DateTime。操纵日期要好得多。但是,如果您出于某种原因想坚持使用字符串,则可以在排序时转换为日期。

public class SortbyDate :IComparer<OilChange>
{
    public int Compare(OilChange x, OilChange y)
    {
        DateTime dateX = Convert.ToDateTime(x.ServiceDate);
        DateTime dateY = Convert.ToDateTime(y.ServiceDate);
        return dateX.CompareTo(dateY);
    }
}

如果您的问题只是格式化日期,请尝试:

string date = String.Format("{0:MM/dd/yyyy}", dateTimeValue);

阅读更多here

【讨论】:

  • 谢谢吉尔赫姆!那行得通!也感谢乔纳森!
【解决方案2】:

如果将其作为字符串进行排序,则 11 将排在前面,例如 2,使 11 月排在 2 月之前。如果它所代表的值是一个日期,您可能应该将它存储和操作为一个日期。

这是我用于日期交换的函数

public string SwitchDate(string date)
{
    Debug.Log ("Date IN: Switch " + date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}", inputSections[2], inputSections[0], inputSections[1]); 
    Debug.Log ("Date OUT: Switch " + ServiceDate);

    return ServiceDate;
}

string SwitchbackDate(string date)
{
    Debug.Log ("Switchback In: " +date);
    string[] inputSections=date.Split('/');
    string ServiceDate=string.Format("{0}/{1}/{2}",inputSections[1], inputSections[2], inputSections[0]); 
    Debug.Log ("Switchback Out: " + ServiceDate);

    return ServiceDate;
}

【讨论】:

  • 删除时间、冒号等无关信息的最佳方法是什么?
  • 当您输出日期(在网格、标签或其他任何地方)时,ToString() 使用日期格式。例如myDate.ToString("dd/MMM/yyyy") 参见:docs.microsoft.com/en-us/dotnet/standard/base-types/… 了解更多详情
  • 干得漂亮!
  • 我返回并在一些旧数据中添加了 11/1/xxxx,不幸的是,它再次将日期推到了顶部。有什么想法吗?
  • 如何将 11/1/xxxx 转换为日期时间对象?如果您使用DateTime.Parse,它可能会反转月份和日期。最好是 DateTime.ParseExact 使用日期时间格式来强制执行月/日顺序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 2015-09-08
  • 2015-04-25
相关资源
最近更新 更多