Reputation: 53
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
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
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