在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
?
答案 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;
}
值得注意的是:
GregorianCalendar
class用于保留您对Java GregorianCalendar
class getTimeInMillis
method on the Calendar
class返回自纪元以来的毫秒数; .NET没有等价物,但它确实返回从0001年1月1日到Ticks
property的纳秒数。这用于转换为/来自纳秒。DateTime
structure时,删除秒组件就像将0传递给代表timestamp
的新实例一样简单。TimeSpan
structure