Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

.net - How can I specify the latest time of day with DateTime

I am using a System.DateTime object to allow a user to select a date range. The user is only able to select a date (not time) using a third party calendar so I will need to automatically specify the time of day it should use (ie: 00:00:00 or 23:59:59) after the date is chosen.

How can I specify the time after the date is already stored as a DateTime object by the calendar selector? I could use the AddHours, AddMinutes, AddSeconds methods but those are relative to the current time which may not be 00:00:00.

The startDate will need to have a time of 00:00:00 and endDate have a time of 23:59:59 to account for the entire days.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you already have a DateTime object created and want to replace the time with the 11:59:59PM for that given date, then you can use the .Date property to get the date with time set to 00:00:00 and then add the hours, minutes and seconds. For example:

var dt = yourDateInstance.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

If by latest time, you mean 11:59:59 PM, then this should also work:

var dt = new DateTime(Now.Year, Now.Month, Now.Day, 23, 59, 59);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...