简体   繁体   English

将DateTime.Now转换为秒

[英]Convert DateTime.Now to Seconds

I am trying to write a function that will convert a DateTime.Now instance to the number of seconds it represents so that I can compare that to another DateTime instance. 我正在尝试编写一个函数,将DateTime.Now实例转换为它表示的秒数,以便我可以将它与另一个DateTime实例进行比较。 Here is what I currently have: 这是我目前拥有的:

public static int convertDateTimeToSeconds(DateTime dateTimeToConvert)
    {
        int secsInAMin = 60;
        int secsInAnHour = 60 * secsInAMin;
        int secsInADay = 24 * secsInAnHour;
        double secsInAYear = (int)365.25 * secsInADay;

        int totalSeconds = (int)(dateTimeToConvert.Year * secsInAYear) + 
                       (dateTimeToConvert.DayOfYear * secsInADay) +
                       (dateTimeToConvert.Hour * secsInAnHour) +
                       (dateTimeToConvert.Minute * secsInAMin) + 
                       dateTimeToConvert.Second;

        return totalSeconds;
    }

I realize that I am truncating the calculation for seconds in a year, but I don't need my calculation to be precise. 我意识到我在一年内截断了秒的计算,但我不需要我的计算精确。 I'm really looking to know if the method that I am using to calculate seconds is correct. 我真的想知道我用来计算秒数的方法是否正确。

Does anyone have anything that could better compute seconds given from a DateTime object? 有没有人能够更好地计算从DateTime对象给出的秒数?

Also, Should the return type be int64 if I am coding in C# if I am going to calculate all the seconds since 0 AD? 另外,如果我要用C#编码,如果我要计算自0 AD以来的所有秒数,那么返回类型应该是int64吗?

The DateTime type supports comparison operators : DateTime类型支持比较运算符

if (dateTimeA > dateTimeB)
{
    ...

This also works for DateTime values returned by DateTime.AddSeconds : 这也适用于DateTime.AddSeconds返回的DateTime值:

if (dateTimeA.AddSeconds(42) > dateTimeB)
{
    ...

If you really want the number of seconds that elapsed since 01/01/0001 00:00:00 , you can calculate the difference between the two DateTime values. 如果您确实需要自01/01/0001 00:00:00以来经过的秒数 ,则可以计算两个DateTime值之间的差异。 The resulting TimeSpan value has a TotalSeconds property: 生成的TimeSpan值具有TotalSeconds属性:

double result = DateTime.Now.Subtract(DateTime.MinValue).TotalSeconds;

It really doesn't make sense to convert a DateTime object to seconds. 将DateTime对象转换为秒确实没有意义。 Seconds only make sense if you are dealing with a length of time (TimeSpan). 只有在处理一段时间(TimeSpan)时,秒才有意义。 Should you want to compare two dates to get the number of seconds between them: 您是否要比较两个日期以获得它们之间的秒数:

TimeSpan diff = DateTime.Now - PreviousDateTime;
double seconds = diff.TotalSeconds;

See suggestion from thread below: 请参阅以下主题中的建议:

How do I convert ticks to minutes? 如何将刻度转换为分钟?

TimeSpan.FromTicks(DateTime.Now.Ticks).TotalSeconds; 

If the purpose is finding the number of seconds between two dates, you'd be much better off using the TimeSpan object. 如果目的是找到两个日期之间的秒数,那么使用TimeSpan对象会好得多。

TimeSpan span = date2 - date1;
double seconds = span.TotalSeconds;

If you want to compare 2 DateTime object, why just not use the provided operators? 如果要比较2个DateTime对象,为什么不使用提供的运算符? http://msdn.microsoft.com/en-us/library/aa326723%28v=VS.71%29.aspx http://msdn.microsoft.com/en-us/library/aa326723%28v=VS.71%29.aspx

DateTime a, b;
if (a > b) //a is after b

Assuming you really need to get at the seconds for the datetime object, you could directly get the "Ticks" property from it. 假设您确实需要获取datetime对象的秒数,您可以直接从中获取“Ticks”属性。 These aren't in seconds but you can easily divide by the proper factor to convert the Ticks to seconds. 这些不是几秒钟,但您可以轻松划分适当的因素,将Ticks转换为秒。 See: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx 请参阅: http//msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

So, something like: 所以,像:

        DateTime.Now.Ticks/TimeSpan.TicksPerSecond

I would use the TimeSpan class to get the exact difference between two DateTime instances. 我会使用TimeSpan类来获取两个DateTime实例之间的确切差异。 Here is an example: 这是一个例子:

  DateTime dt1 = DateTime.Now;
  DateTime dt2 = new DateTime(2003,4,15);
  TimeSpan ts = dt1.Subtract(dt2);

Once the TimeSpan value ( ts , in the code snippet above) is available, you can examine its values to correctly convert the TimeSpan to a given number of seconds. 一旦TimeSpan值( ts ,在上面的代码片段中)可用,您可以检查其值以将TimeSpan正确转换为给定的秒数。

Using a TimeSpan to get the elapsed time between two DateTimes is probably the best way to go but if you really want to get the number of seconds for a given DateTime you could do something like the following: 使用TimeSpan来获取两个DateTime之间的经过时间可能是最好的方法,但是如果你真的想获得给定DateTime的秒数,你可以执行以下操作:

DateTime dateTimeToConvert = DateTime.Now;
TimeSpan tsElapsed = dateTimeToConvert - DateTime.MinValue;
return tsElapsed.TotalSeconds;

Note that tsElapsed.TotalSeconds is a Double, not an Int. 请注意,tsElapsed.TotalSeconds是Double,而不是Int。

Do note that the goal is to get the number of seconds since DateTime.MinVal (the first day of the calendar). 请注意,目标是获取自DateTime.MinVal(日历的第一天)以来的秒数。 I say this, because I see all of these answers for "you do time comparisons like this... add in the object, multiply by that object and do cross-calculus on them, divide by the quotient of the summed result, and Boom! not what you asked." 我这样说,因为我看到所有这些答案都是“你做这样的时间比较......加入对象,乘以那个对象并对它们进行交叉计算,除以求和结果的商,然后加速不是你问的。“

There's a really simple answer here. 这里有一个非常简单的答案。 Ticks are 100-nanosecond increments. 刻度是100纳秒的增量。 DateTime object.Ticks is the number of ticks that have occurred since 1/1/0001. DateTime object.Ticks是自1/1/0001以来发生的刻度数。 Ie, year zero. 即,零年。 There are 10 million nanoseconds in a second. 一秒钟就有1000万纳秒。 so... 所以...

    public static long convertDateTimeToSeconds(DateTime dateTimeToConvert) {
        // According to Wikipedia, there are 10,000,000 ticks in a second, and Now.Ticks is the span since 1/1/0001. 
        long NumSeconds= dateTimeToConvert.Ticks / 10000000;
        return NumSeconds;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM