C# 如何将 DateTime Now 转换为秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1292819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:45:50  来源:igfitidea点击:

how to Convert DateTime Now To second

c#datetime

提问by monkey_boys

I have the input 15:20:30

我有输入 15:20:30

I want to convert to seconds.

我想转换为秒。

采纳答案by Lloyd Powell

Seeing as though you haven't specified the question properly I have interpreted it to represent 15 hours 20 minutes and 30 seconds, as opposed to DateTime.Now. (Obviously this is the same as "How many seconds since midnight")

好像您没有正确指定问题,我已将其解释为表示 15 小时 20 分 30 秒,而不是 DateTime.Now。(显然这与“自午夜以来的秒数”相同)

  TimeSpan MySpan = new TimeSpan(15, 20, 30);
  MySpan.TotalSeconds;

Although if you're only wanting the Seconds from the current DateTime.Now (this is not the TotalSeconds, just the current minutes seconds), just use:

虽然如果您只想要当前 DateTime.Now 的秒数(这不是 TotalSeconds,只是当前的分钟秒数),只需使用:

  DateTime.Now.Second

回答by Richard

var dt = DateTime.Now;
var ticks = dt.Ticks;
var seconds = ticks/TimeSpan.TicksPerSecond;

Each tick is 100 nanoseconds.

每个刻度是 100 纳秒。

回答by Martin Liversage

Not sure what you really want, but if you want to compute the number of seconds from 15 hours, 20 minutes and 30 seconds you can do this:

不确定你真正想要什么,但如果你想计算 15 小时 20 分 30 秒的秒数,你可以这样做:

Int32 GetSeconds(Int32 hours, Int32 minutes, Int32 seconds) {
  return ((hours*60) + minutes)*60 + seconds;
}