【问题标题】:Add X days to timestamp将 X 天添加到时间戳
【发布时间】:2015-07-19 10:13:48
【问题描述】:

标题可能有点混乱,但我不知道如何命名。我正在为一个游戏编写一个模拟器,而该游戏正在使用 Timestamp 来计算溢价时间。

我需要的是一个获取当前时间戳的函数,然后是一个为其添加 x 天的函数,例如:

int daysToAdd = 10;
long Timestamp_normal = GetTimestamp();
long newTimestamp = AddDays(Timestamp_normal, daysToAdd);

亲切的问候

【问题讨论】:

    标签: c# timestamp


    【解决方案1】:

    您可以使用 DateTime 进行计算并将其转换为时间戳:

    var startDate = DateTime.Now;
    long startTimeStamp = startDate.ToTimeStamp();
    
    var endDate = startDate.AddDays(1);
    long endTimeStamp = endDate.ToTimeStamp();
    

    有多种方法可以从 DateTime 生成“时间戳”(取决于您对时间戳的定义),因此请选择任何可行的方法并将其移至 DateTime 扩展方法,如上所示:

    public static class DateTimeExtensions
    {
        public static long ToTimeStamp(this DateTime input)
        {
            // your implementation here
        }
    }
    

    有关实现,请参阅Function that creates a timestamp in c#How to convert datetime to timestamp using C#/.NET (ignoring current timezone)How to get the unix timestamp in C# 等。

    【讨论】:

    • .ToTimeStamp 似乎不存在。
    • 不,那是我编造的扩展方法。答案就在其中。
    【解决方案2】:

    可能您只是想获得那天的Ticks

    long ts1 = DateTime.Now.AddDays(10).Ticks;
    

    【讨论】:

    • 问题不是“如何从日期时间制作时间戳”,而且这个问题之前已经回答过很多次了(请参阅我的回答中的三个链接)。
    • @CodeCaster,问题不是说一个获取当前时间戳的函数,然后是一个添加x天的函数?不过,我没有看到需要特定功能。
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2010-10-26
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多