C# Datetime.now 作为 TimeSpan 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11929554/
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-09 19:44:52  来源:igfitidea点击:

Datetime.now as TimeSpan value?

c#datetimetimespanseconds

提问by MrMAG

I need the current Datetime minus myDate1in seconds.

我需要myDate1以秒为单位减去当前日期时间。

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;

TimeSpan myDateResult = new TimeSpan();

myDateResult = myDate2 - myDate1;

.
.
I tried different ways to calculate but to no effect.

.
.
我尝试了不同的计算方法,但没有效果。

TimeSpan mySpan = new TimeSpan(myDate2.Day, myDate2.Hour, myDate2.Minute, myDate2.Second);

.
The way it's calculated doesn't matter, the output should just be the difference these to values in seconds.

.
它的计算方式无关紧要,输出应该只是这些值与以秒为单位的值的差异。

采纳答案by Guffa

Your code is correct. You have the time difference as a TimeSpanvalue, so you only need to use the TotalSecondsproperty to get it as seconds:

你的代码是正确的。你有时间差作为一个TimeSpan值,所以你只需要使用TotalSeconds属性来获取它作为秒:

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;

TimeSpan myDateResult;

myDateResult = myDate2 - myDate1;

double seconds = myDateResult.TotalSeconds;

回答by Adriaan Stander

Have you tried something like

你有没有尝试过类似的东西

DateTime.Now.Subtract(new DateTime(1970, 1, 9, 0, 0, 00)).TotalSeconds

DateTime.Subtract Method (DateTime)

DateTime.Subtract 方法 (DateTime)

TimeSpan.TotalSeconds Property

TimeSpan.TotalSeconds 属性

回答by Mahdi Tahsildari

you need to get .TotalSecondsproperty of your timespan :

您需要获取.TotalSeconds时间跨度的属性:

DateTime myDate1 = new DateTime(2012, 8, 13, 0, 05, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate2 - myDate1;
MessageBox.Show(myDateResult.TotalSeconds.ToString());

回答by Chaturvedi Dewashish

You can use Subtractmethod:

您可以使用Subtract方法:

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan ts = myDate2.Subtract(myDate1);
MessageBox.Show(ts.TotalSeconds.ToString());

回答by Prerna

TimeSpan myDateResult;

myDateResult = DateTime.Now.Subtract(new DateTime(1970,1,9,0,0,00));
myDateResult.TotalSeconds.ToString();

回答by YC Chiranjeevi

Code:

代码:

TimeSpan myDateResult = DateTime.Now.TimeOfDay;