如何从.NET中的Unix纪元中以毫秒为单位的日期和时间中删除秒数?

时间:2011-11-30 19:42:03

标签: c# java .net datetime

在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

中实现此功能

1 个答案:

答案 0 :(得分:3)

在.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;
}

值得注意的是: