【问题标题】:How can I remove the seconds from a date and time represented in milliseconds from the Unix epoch in .NET? [closed]如何从 .NET 中的 Unix 纪元中删除以毫秒为单位的日期和时间的秒数? [关闭]
【发布时间】:2012-01-10 01:00:15
【问题描述】:

在 Java 中,我会这样做(请注意,它也会从 Unix epoch 返回日期和时间,以毫秒为单位):

private static long removeSeconds(long timestamp)
{
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTimeInMillis(timestamp);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis();
}

如何在.NET 中实现这一点?

【问题讨论】:

    标签: c# java .net datetime


    【解决方案1】:

    在 .NET 中,假设您想要自 Unix 纪元以来的毫秒数,但删除了秒数,我会执行以下操作:

    private static readonly GregorianCalendar DefaultGregorianCalendar = 
        new GregorianCalendar();
    
    private static readonly DateTime UnixEpoch = 
        new DateTime(1970, 1, 1, DefaultGregorianCalendar);
    
    private static long RemoveSeconds(long timestamp)
    {
        // Convert the timestamp into a DateTime.
        var dt = DefaultGregorianCalendar.AddMilliseconds(UnixEpoch, timestamp);
    
        // Get the time in minutes.  The zero has the effect of removing the
        // seconds component.
        var newTime = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0, 
            DefaultGregorianCalendar);
    
        // Subtract the epoch from the new time.
        TimeSpan difference = newTime - dt;
    
        // Return the total milliseconds.
        return (long) difference.TotalMilliseconds;
    }
    

    注意:

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2021-06-11
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多