Skip to content

Instantly share code, notes, and snippets.

@Pie001
Last active December 21, 2016 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pie001/da52724a61831072916c to your computer and use it in GitHub Desktop.
Save Pie001/da52724a61831072916c to your computer and use it in GitHub Desktop.
DateTimeもしくはtimestampより経過時間を取得
// 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日");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment