System.currentTimeMillis()
C#中Java的等价物是什么?
替代:
private static readonly DateTime Jan1st1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static long CurrentTimeMillis() { return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds; }
Java中常见的习惯用法是currentTimeMillis()
用于计时或调度目的,你对自1970年以来的实际毫秒数不感兴趣,而是计算一些相对值并比较以后currentTimeMillis()
对该值的调用.
如果这就是你要找的东西,那么等效的C#就是Environment.TickCount
.
如果您对TIMING感兴趣,请添加对System.Diagnostics的引用并使用秒表.
例如:
var sw = Stopwatch.StartNew(); ... var elapsedStage1 = sw.ElapsedMilliseconds; ... var elapsedStage2 = sw.ElapsedMilliseconds; ... sw.Stop();
在System.currentTimeMillis()
Java中返回从1/1/1970以毫秒为单位的当前时间
c#将是
public static double GetCurrentMilli() { DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0,0,DateTimeKind.Utc); TimeSpan javaSpan = DateTime.UtcNow - Jan1970; return javaSpan.TotalMilliseconds; }
编辑:按建议制作utc :)
我们也可以稍微看一下它作为扩展方法,以便它挂起DateTime类:
public static class DateTimeExtensions { private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static long currentTimeMillis(this DateTime d) { return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds); } }
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()