[英]How can I find the current time as a long in C#?
我有这个Java代码,我想在C#中做同样的事情:
long now =System.currentTimeMillis()/1000;
Having checked what java returns (1970/1/1 etc): 检查了java返回的内容 (1970/1/1等):
static readonly DateTime epoch=new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
...
long ms = (long)(DateTime.UtcNow - epoch).TotalMilliseconds;
long result = ms / 1000;
There's no direct equivalent to this in C# (and by that I mean in a single line), but assuming you just want something functionally similar, but not necessarily the Java implementation you can use: 在C#中没有直接等同于此(我的意思是在一行中),但假设您只是想要功能相似的东西,但不一定是Java实现,您可以使用:
DateTime.Now.Ticks;
Ticks are: 蜱虫是:
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.
此属性的值表示自0001年1月1日午夜12:00:00起经过的100纳秒间隔的数量,表示DateTime.MinValue。
http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
And this may not be relevant to you at all, but getting time in ticks/ms is often used for microbenchmarks to measure how long something takes in your code, and C# has a better class for that, namely Stopwatch
. 这可能与你无关,但是以时间/秒为单位的时间通常用于微基准测试,以衡量代码中的内容需要多长时间,而C#有更好的类,即
Stopwatch
。 It's easier to use and more accurate too. 它更容易使用,也更准确。
Use it like: 使用它像:
Stopwatch s = Stopwatch.StartNew();
s.Stop();
Console.Write(s.Elapsed);
This may not be what you're trying to do, but useful to know anyway. 这可能不是你想要做的,但无论如何都很有用。
currenTimeMillis给出自1970年1月1日以来的毫秒数,所以如果您需要完全相同的答案,您需要以下内容:
((DateTime.Now - new DateTime(1970,1,1)).TotalMilliseconds) / 1000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.