liushijie
2025-03-14 7f2111c25184bcc3ced97cea322e55b3a105dfc5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LifePayment.Domain.Shared;
 
public static class TimeUtility
{
    /// <summary>
    /// 获取过去多长时间字符串
    /// ToDo后续可以优化为根据指定的时间间隔文本字典来更加灵活的返回对应的文本
    /// </summary>
    /// <param name="sourceTime"></param>
    /// <param name="now"></param>
    /// <returns></returns>
    public static string GetBeforeTimeStr(DateTime sourceTime, DateTime? now = null)
    {
        string result = null;
        now = now ?? DateTime.Now;
 
        if (now < sourceTime)
        {
            return result;
        }
 
        var timeSpan = now.Value.Date - sourceTime.Date;
 
        switch (timeSpan.TotalDays)
        {
            case >= 1 and < 2:
                result = $"昨天";
                break;
 
            case >= 2 and < 3:
                result = $"前天";
                break;
 
            case >= 3 and < 30:
                result = $"{Math.Floor(timeSpan.TotalDays)}天前";
                break;
 
            case >= 30:
                result = $"{Math.Floor(timeSpan.TotalDays / 30)}月前";
                break;
 
            default:
                timeSpan = now.Value - sourceTime;
                if (timeSpan.TotalHours >= 1)
                {
                    result = $"{Math.Floor(timeSpan.TotalHours)}小时前";
                }
                else
                {
                    result = $"刚刚";
                }
                break;
        }
 
        return result;
    }
 
}