/// <summary>
/// Extension methods for <see cref="DateTime"/>.
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Converts a DateTime to a Unix Timestamp
/// </summary>
/// <param name="target">This DateTime</param>
/// <returns></returns>
public static double ToUnixTimestamp(this DateTime target)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var diff = target - origin;
return Math.Floor(diff.TotalSeconds);
}
/// <summary>
/// Converts a Unix Timestamp in to a DateTime
/// </summary>
/// <param name="unixTime">This Unix Timestamp</param>
/// <returns></returns>
public static DateTime FromUnixTimestamp(this double unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return epoch.AddSeconds(unixTime);
}
/// <summary>
/// Gets the value of the End of the day (23:59)
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static DateTime ToDayEnd(this DateTime target)
{
return target.Date.AddDays(1).AddMilliseconds(-1);
}
/// <summary>
/// Gets the First Date of the week for the specified date
/// </summary>
/// <param name="dt">this DateTime</param>
/// <param name="startOfWeek">The Start Day of the Week (ie, Sunday/Monday)</param>
/// <returns>The First Date of the week</returns>
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
var diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
diff += 7;
return dt.AddDays(-1 * diff).Date;
C# DateTime 扩展类 常用方法
于 2024-05-30 17:39:17 首次发布