csharp 一个简单的帮助器,用于转换为/从unix时间戳和计算时间。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 一个简单的帮助器,用于转换为/从unix时间戳和计算时间。相关的知识,希望对你有一定的参考价值。

#region License

// Copyright (c) 2014 Harry Martinez <harry@zumicts.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#endregion

#region

using System;

#endregion

namespace Zumicts.Utility
{
    public static class TimeHelper
    {
        public readonly static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

        public static long GetCurrentUnixTimestamp()
        {
            return (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
        }

        public static DateTime ConvertFromUnixTimestamp(long unixTime)
        {
            return UnixEpoch.AddSeconds(unixTime);
        }

        public static long ConvertToUnixTimestamp(DateTime time)
        {
            return (long)(time - UnixEpoch).TotalSeconds;
        }

        public static string ToTimeSince(long unixTime)
        {
            return ToTimeSince(ConvertFromUnixTimestamp(unixTime));
        }

        public static string ToTimeSince(DateTime time)
        {
            var now = DateTime.UtcNow;

            var since = now - time;

            if (since.TotalSeconds < 60)
                return Math.Floor(since.TotalSeconds) + "s ago";
            if (since.TotalMinutes < 60)
                return Math.Floor(since.TotalMinutes) + "m ago";
            if (since.TotalHours < 24)
                return Math.Floor(since.TotalHours) + "h ago";
            return Math.Floor(since.TotalDays) + "d ago";
        }
    }
}

以上是关于csharp 一个简单的帮助器,用于转换为/从unix时间戳和计算时间。的主要内容,如果未能解决你的问题,请参考以下文章

csharp 用于从csproj unity 2018中排除着色器文件的后处理器生成

csharp 一种将输入图像转换为不同格式的简单工具。

Java - 将 doc/docx 文件转换为 chm 文件

csharp 从继承类型转换为特定类型

csharp itinerar a traves de un diccionario

Java&amp;Xml教程JAXB实现XML与Java对象转换