Young programmer
Young programmer

Reputation: 53

How to get day start date in seconds based on current date in seconds

As in the title, I get the current date in seconds and I need to get the start of the day also in seconds, example function

private long? getStartOfDay(long? dateVal){
    return ...
}

date with 0 number of seconds will return midnight Jan 1 1970

Upvotes: 0

Views: 632

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61932

You mean like this?

    private static long? getStartOfDay(long? dateVal) {
        return dateVal - dateVal % 86400L;
    }

Just truncating down to nearest multiple of 24 * 60 * 60.

Will not work with negative values, so either include a check that will throw an ArgumentOutOfRangeException, or change to ulong.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You are working with Unix date. To get DateTime from seconds:

 double seconds = ...

 // .Date to get rid of TimeOfDay (Hour, Minute, Second) component 
 DateTime startDate = DateTime.UnixEpoch.AddSeconds(seconds).Date;

Or if you want to get local time Date

 DateTime startDate = DateTime.UnixEpoch.AddSeconds(seconds).ToLocalTime().Date;

To get seconds from DateTime:

 DateTime myDate = ...

 var seconds = (myDate.ToUniversalTime() - DateTime.UnixEpoch).TotalSeconds;

Upvotes: 1

Related Questions