4

I have a method that returns a List<DateTime> but the code I run inside the method gives me a List<string>

How can I convert the List<string> to a List<DateTime> for my return line?

It's basically a method that takes in a List of photos and returns a List of their date's taken property;

            //retrieves the datetime WITHOUT loading the whole image
    public List<DateTime> GetDateTakenFromImage(List<string> path)
    {
        List<string> dateTaken = new List<string>();
        int cnt = 0;
        while (cnt < path.Count())
        {


            using (FileStream fs = new FileStream(path[cnt], FileMode.Open, FileAccess.Read))
            using (Image myImage = Image.FromStream(fs, false, false))
            {

                PropertyItem propItem = myImage.GetPropertyItem(36867);
                dateTaken[cnt] = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
            }
            cnt++;
        }

        return dateTaken;

I got this code from the website so I'm not entirely sure if I can make it return them to a List<DateTime>

I think I can make the provided answers work for this code though.

Thanks!

5
  • 1
    Probably best to modify the inner code to produce a DateTime directly. Show us the code.
    – p.s.w.g
    Jan 15, 2014 at 3:12
  • that code won't work (sorry it will compile but you will get an ArgumentOutOfRange exception in runtime),you are trying to add new items to the generic list with indexer : dateTaken[cnt] = ... but you can't, see my question Jan 15, 2014 at 3:29
  • @Selman22 thanks! I originally had a loop outside this method that just extracted each date taken prop one by one. But I was getting the ArgumentOutOfRange exception during runtime and had no idea why!!! I thought I could get around this by putting the loop inside the method
    – teepee
    Jan 15, 2014 at 3:53
  • @teepee use Add method instead, dateTaken.Add(...) Jan 15, 2014 at 3:55
  • @Selman22 Finally! thank you so much it worked, that was driving me nuts that I couldn't figure it out
    – teepee
    Jan 15, 2014 at 4:12

2 Answers 2

21

If you know all the string's will parse properly as a DateTime, you can do something like:

List<string> strings = new List<string>() { "2014-01-14" };

List<DateTime> dates = strings.Select(date => DateTime.Parse(date)).ToList();
1
  • +1 this is a more elegant solution than the one I had in mind.
    – pcnThird
    Jan 15, 2014 at 3:41
4

Assuming the string is in the proper format:

List<DateTime> dateTimeList = new List<DateTime>();

foreach (string s in stringList)
    dateTimeList.Add(Convert.ToDateTime(s));

 return dateTimeList;

See http://msdn.microsoft.com/en-us/library/cc165448.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.