Convert time string to DateTime in c#

This is as simple as parsing a DateTime with an 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 allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.

To answer the second part

How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.

This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed 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);

You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

string inTime="14:00";
DateTime d;

if(DateTime.TryParse(inTime,out d))
{
   Console.WriteLine("DateTime : " + d.ToString("dd-MM-yyyy HH:mm:SS"));
} 

Working example here


There is a datetime constructor for

public DateTime(
    int year,
    int month,
    int day,
    int hour,
    int minute,
    int second
)

So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.

Tags:

C#

Datetime