c# - 像 StackoverFlow 一样设置日期时间格式

标签 c# datetime datetime-format

Possible Duplicates:
Fuzzy date algorithm
How do I calculate relative time?

嗨,

如何像这样格式化日期时间?

1分钟前

1小时前

8 月 15 日 15:00 提问

最佳答案

您需要做的第一件事是确定日期的差异。

DateTime 上使用 Subtract() 方法。它返回一个TimeSpan,这可以方便地满足您的需求。

TimeSpan mySpan = DateTime.Now.Subtract( myPostedDate );

然后,您需要找到最重要的非零时间元素。如果你要处理几天的事情,事情就很容易了。较小的面额需要更多的工作。包含代码。

TimeSpan mySpan = DateTime.Now.Subtract(myRecorded);
string  myDenom = 
  mySpan.Days    > 0 ? "day" : 
  mySpan.Hours   > 0 ? "hour" : 
  mySpan.Minutes > 0 ? "minute" : "second";

string myOutput = String.Empty;

int myNumeral;

// if we're dealing with days, a format string will suffice
if (myDenom == "day")
{
    // HH - 24 hour clock
    myOutput = String.Format("{0:MMM dd} at {0:HH}:{0:mm}", myRecorded);
}
else
{
    // put the right denomination into myNumeral
    switch (myDenom)
    {
        case "second":
            myNumeral = mySpan.Seconds;
            break;
        case "minute":
            myNumeral = mySpan.Minutes;
            break;
        default:
            myNumeral = mySpan.Hours;
            break;
    }

    // add an s to myNumeral when > 1
    myDenom += (myNumeral > 1) ? "s" : String.Empty;
    myOutput = String.Format("{0} {1} ago", myNumeral, myDenom);
}

// myOutput now contains formatted string

关于c# - 像 StackoverFlow 一样设置日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2139022/

相关文章:

c# - 使用 Parallel.For 和 EPPlus 创建 Excel 工作表

c# - 如何使用 .net 获取用户的 IP 地址?

ruby-on-rails - 为什么Rails总是将日期时间显示为1/1/2000-具有正确的时间

python - 将时间戳转换为月份名称和年份作为数据框列名称

MySQL 如何按时间进行操作,如 30 :47 (30 minutes and 47 seconds)

c# - Xamarin Forms 中的后台计时器 [PCL]

c# - 从相对 Uri c# 中截断 QueryString 的干净方法

sql - 选择给定缺失记录的数据的最新值

ios - 如何在ios中获取今天日期的开始和结束时间?

jquery datetimepicker的自定义时间格式