It is as simple as parsing a DateTime with the exact format.
Achievable with
var dateStr = "14:00"; var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply lets you pass the format string you want as a parsing string to return a DateTime structure. Now the Date mark of this line will be set by default until today's date when no date is provided.
To answer the second part
How can I get a DateTime object with the current date as the date, if only the current time is already 14:00:01, then the date should be the next day.
It is also simple, since we know that DateTime.ParseExact will return to today's date (since we did not provide a date), we can compare our parsed date with DateTime.Now . If DateTime.Now larger than our syntax date, we add 1 day to our parsed date.
var dateStr = "14:00"; var now = DateTime.Now; var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None); if (now > dateTime) dateTime = dateTime.AddDays(1);
Nico
source share