Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

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?

like image 950
TheDevOpsGuru Avatar asked Nov 05 '10 20:11

TheDevOpsGuru


People also ask

How do I convert datetime to seconds?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How do you use now 2 in Python?

Get Current Time in PythonUse the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.

How do you convert Timedelta to seconds?

Use datetime. timedelta. total_seconds() to convert timedelta to seconds. Call timedelta.


1 Answers

The DateTime type supports comparison operators:

if (dateTimeA > dateTimeB)
{
    ...

This also works for DateTime values returned by DateTime.AddSeconds:

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. The resulting TimeSpan value has a TotalSeconds property:

double result = DateTime.Now.Subtract(DateTime.MinValue).TotalSeconds;
like image 104
dtb Avatar answered Oct 13 '22 01:10

dtb