简体   繁体   中英

In C#, how can I convert a string time (formatted as HH:mm) into a DateTime variable?

I have a string that represents a time formatted as "HH:mm", say for example "8:15" (assuming the time is in 24 hour format). In C#, How can I convert that into a DateTime instance where the date is today's date and the time is 8:15 AM?

string ds = "8:15";
string[] parts = ds.Split(new[] { ':' });
DateTime dt = new DateTime(
                   DateTime.Now.Year,
                   DateTime.Now.Month,
                   DateTime.Now.Day,
                   Convert.ToInt32(parts[0]), 
                   Convert.ToInt32(parts[1]));
 DateTime.Parse(DateTime.Now.Date.ToString() + " " + yourString);
       string time ="8:15";            
       DateTime date = DateTime.Parse(DateTime.Now.ToString("M/d/yyyy ") + time);

You can probably parse the time using TimeSpan.ParseExact and then add it to today's date by using DateTime.Add .

Given that your time is in a variable like this:

var timeText = "8:15";

Parse the time like this:

var time = TimeSpan.ParseExact(timeText, "h:mm", /*todo*/);

Fill the last argument depending on your requirements.

Then add it to today's date:

DateTime.Today.Add(time);

Assuming situation for current date:

    string time ="8:15";
    var dt = Convert.ToDateTime(String.Format("{0} {1}",
             DateTime.Now.ToShortDateString(),time));

If you have a valid date in string then, you can use. Also you can use DateTime.TryParse() to check for a valid date.

 var date ="01/01/2014";
  var dt = Convert.ToDateTime(String.Format("{0} {1}",
                 date,time));

You will get output

01/06/2014 08:15:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM