IT業界のすみっこ暮らし

ふと気がついたときの記録

timestamp/DateTimeから経過時間を取得する(C#)

DateTimeより経過時間を取得

public static string GetLapsedTimeFromDateTime(DateTime dt)
{
    string timeString = string.Empty;

    TimeSpan ts = DateTime.Now.Subtract(dt);

    int DayPeriod = Math.Abs(ts.Days);

    if (DayPeriod < 1)
    {
        int HourPeriod = Math.Abs(ts.Hours);

        if (HourPeriod < 1)
        {
            int MinutePeriod = Math.Abs(ts.Minutes);
            if (MinutePeriod < 1)
            {
                int SecondPeriod = Math.Abs(ts.Seconds);
                return SecondPeriod.ToString() + "秒前";
            }
            else
            {
                return MinutePeriod.ToString() + "分前";
            }
        }
        else
        {
            return HourPeriod.ToString() + "時間前";
        }
    }
    else if ((DayPeriod > 0) && (DayPeriod < 7))
    {
        return DayPeriod.ToString() + "日前";
    }
    else if (DayPeriod == 7)
    {
        return "1週間前";
    }
    else
    {
        return dt.ToString("yyyy年MM月dd日");
    }
}

timestampより経過時間を取得

public static string GetLapsedTimeFromTimestamp(string timestamp)
{
    if (timestamp == "")
        return string.Empty;

    if (timestamp == null)
        return string.Empty;

    if (timestamp == "0")
        return string.Empty;

    string timeString = string.Empty;

    DateTime dt = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

    dt = dt.AddSeconds(Convert.ToDouble(timestamp));

    TimeSpan ts = DateTime.Now.Subtract(dt);

    int DayPeriod = Math.Abs(ts.Days);

    if (DayPeriod < 1)
    {
        int HourPeriod = Math.Abs(ts.Hours);

        if (HourPeriod < 1)
        {
            int MinutePeriod = Math.Abs(ts.Minutes);
            if (MinutePeriod < 1)
            {
                int SecondPeriod = Math.Abs(ts.Seconds);
                return SecondPeriod.ToString() + "秒前";
            }
            else
            {
                return MinutePeriod.ToString() + "分前";
            }
        }
        else
        {
            return HourPeriod.ToString() + "時間前";
        }
    }
    else if ((DayPeriod > 0) && (DayPeriod < 7))
    {
        return DayPeriod.ToString() + "日前";
    }
    else if (DayPeriod == 7)
    {
        return "1週間前";
    }
    else
    {
        return dt.ToString("yyyy年MM月dd日");
    }
}