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?
Asked
Active
Viewed 3,622 times
0

Pratik Singhal
- 6,283
- 10
- 55
- 97

leora
- 188,729
- 360
- 878
- 1,366
-
3possible duplicate of [Converting String to DateTime C#.net](http://stackoverflow.com/questions/919244/converting-string-to-datetime-c-net) – Nahum Jan 06 '14 at 05:29
-
@NahumLitvin, that question is about converting both a date and a time into a `DateTime`. This one only concerns times. – Sam Jan 06 '14 at 05:39
-
Keep in mind that this could be problematic if the resulting time is ambiguous or invalid due to a daylight savings change. – Sam Jan 06 '14 at 05:41
-
@Sam The "crux" of the question is the same. – Pratik Singhal Jan 06 '14 at 05:41
-
@Sam please turn back your programmer hat. – Nahum Jan 06 '14 at 05:51
5 Answers
2
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]));

Thomas Weller
- 11,631
- 3
- 26
- 34
-
1The value of `DateTime.Now` could potentially change in between calls to it. It's probably better to store the value in a variable. Also, you can use `DateTime.Today` to simplify some of what you're doing. – Sam Jan 06 '14 at 05:59
0
string time ="8:15";
DateTime date = DateTime.Parse(DateTime.Now.ToString("M/d/yyyy ") + time);

Sid
- 197
- 12
0
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);

Sam
- 40,644
- 36
- 176
- 219
0
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