简体   繁体   English

如何在C#中找到当前时间长?

[英]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.

相关问题 如何查找当前时间是否在C#中的时间范围内 - How can I find if current time fall in time range in c# 给定本地时区和目标时区,我如何找到目标的当前时间C# - Given a local timezone and a target timezone how can I find the target's current time C# 如何在编译时在.net / C#应用程序中找到当前时间和日期? - How do I find the current time and date at compilation time in .net/C# application? 如何在C#中找到文件打开时间? - How can I find a file open time in C#? 如何在c#asp.net中找到不同文化的当前时间,即不同的时区? - How to find Current Time of different culture i.e different timezone in c# asp.net? 如何根据C#中的星期几确定当前时间是否在重复发生的时间范围内? - How can I determine if the current time is within a reoccurring time range based on the day of week in C#? 如何在C#数据工厂中创建长时间运行的一次性管道 - How can I create a one time pipeline run with a long delay in c# data factory 使用c#查找当前的莫斯科时间 - find current moscow time using c# 给定 C# 中的课程时间范围集合,我如何获得当前课程? - How can I get the current lesson, given a collection of lesson time ranges in C#? 如何找出当前对象是否为对象<T>或对象<T,U>在 C# 中 - How can I find out wether the current object is object<T> or object<T,U> in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM