Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<string> to List<DateTime>

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!

like image 465
teepee Avatar asked Nov 29 '22 01:11

teepee


2 Answers

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();
like image 116
mfanto Avatar answered Dec 05 '22 02:12

mfanto


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

like image 30
dursk Avatar answered Dec 05 '22 02:12

dursk