Merge Time String into a DateTime?

L

lucius

I have a string[] of time values that look like this:
"16:00:00"
"18:00:00"
"22:30:30"
I need to convert/merge them to a List<DateTime> so they will be
{1753-01-01 16:00:00}
{1753-01-01 18:00:00}
{1753-01-01 23:30:30}

What is the best way to do that date/time math?

Thanks.
 
M

Mattias Sjögren

I have a string[] of time values that look like this:
"16:00:00"
"18:00:00"
"22:30:30"
I need to convert/merge them to a List<DateTime> so they will be
{1753-01-01 16:00:00}
{1753-01-01 18:00:00}
{1753-01-01 23:30:30}

What is the best way to do that date/time math?

Something like this ought to do it

string[] times = {"16:00:00", "18:00:00", "22:30:30"};
List<DateTime> dates = new List<DateTime>(times.Length);
foreach (string t in times)
{
dates.Add(new DateTime(1735, 1, 1) + TimeSpan.Parse(t));
}


I assume it was a typo that turned 22:30 into 23:30.


Mattias
 
P

Peter Duniho

[...]
What is the best way to do that date/time math?

Best? I don't know. I can tell you what I'd probably do: use the time to
instantiate a DateTime object using Parse(), and then use the resulting
DateTime object's hour, minute, and second properties as part of the
instantiation of a new DateTime object to put in your List<>.

Pete
 
P

Pramod Anchuparayil

Here's an example, I am sure there are other ways....

private IList<DateTime> ConvertToDateTimeList(string[] datetime)
{
return Array.ConvertAll(datetime, new Converter<string,
DateTime>(StringToDate));
}

private DateTime StringToDate(string dateTime)
{
return DateTime.Parse(dateTime);
}
 
P

Pramod Anchuparayil

I have a string[] of time values that look like this:
"16:00:00"
"18:00:00"
"22:30:30"
I need to convert/merge them to a List<DateTime> so they will be
{1753-01-01 16:00:00}
{1753-01-01 18:00:00}
{1753-01-01 23:30:30}

What is the best way to do that date/time math?

Thanks.

Or this...

private IList<DateTime> ConvertToIList(string[] datetime)
{
return Array.ConvertAll(datetime, new Converter<string,
DateTime>(DateTime.Parse));
}

-Pramod
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top