将日期时间字符串列表转换为DateTime值列表

时间:2016-10-27 16:45:08

标签: c# datetime iso8601 take tolist

我对C#来说是全新的。使用SharpDevelop程序。我可以在'for'循环中转换ISO 8601 DateTime值。我确信'records'的ToList方法允许我将所有字符串条目转换为DateTime值,但我无法实现。请帮忙。

var myFormat = string.Empty;
myFormat = "yyyy-MM-ddTHH:mm:ss";
var myDateTime = System.DateTime.Now;
var originTime = new System.DateTime(1970,1,1,0,0,0);
var mySpan = myDateTime.Subtract(new System.DateTime(1970,1,1,0,0,0));
var value = mySpan.TotalSeconds;

using (var sr = new StreamReader(@"C:\Users\me\Desktop\file.csv"))
{
    var reader = new CsvReader(sr);
    IEnumerable<DataRecord1> records = reader.GetRecords<DataRecord1>();
    foreach (DataRecord1 record in records.Take(5)) 
    {
        myDateTime = System.DateTime.ParseExact( record.TimeWhen, myFormat, null );
        mySpan = myDateTime.Subtract( originTime );
        value = mySpan.TotalSeconds;
        seconds = ( float ) myDateTime;
        Debug.Print("{0}", value );
    }
}

4 个答案:

答案 0 :(得分:3)

要从某种类型A的列表转换为B类型的列表,建议您使用Linq Select()方法

using system.Linq;

IEnumerable<DataRecord1> records = reader.GetRecords<DataRecord1>();
List<DateTime> datetimes = records.Select(x => System.DateTime.ParseExact(x.TimeWhen, myFormat, null).ToList();

答案 1 :(得分:1)

您可以使用LINQ来执行此操作

var l = records
    .Select(x=>System.DateTime.ParseExact(x.TimeWhen, myFormat, null))
    .Select(x=>x.Subtract(originTime))
    .Select(x=>mySpan.TotalSeconds)
    .ToList();

答案 2 :(得分:0)

除了使用linq之外,您还可以使用Extension方法来执行此操作:

public static DateTime ToDateTime(this DataRecord1, format)
{
    return System.DateTime.ParseExact(DataRecord1.TimeWhen, format);
}

和他们一样,调用ToDateTime方法:

IEnumerable<DataRecord1> records = reader.GetRecords<DataRecord1>();
List<DateTime> datetimes = new List<DateTime>();
records.ForEach(x => datetimes.Add(x.ToDateTime());

答案 3 :(得分:0)

从签名中你的CsvReader返回一个IEnumerable。是否可以将其转换为列表。对于DateTime转换,我会使用TryParse。即:

var originTime = new System.DateTime(1970, 1, 1);
IEnumerable<DataRecord1> records;

using (var sr = new StreamReader(@"C:\Users\me\Desktop\file.csv"))
{
    var reader = new CsvReader(sr);
    records = reader.GetRecords<DataRecord1>();
}

DateTime t;
var result = from r in records
             let sWhen = r.TimeWhen
             let When = DateTime.TryParse(sWhen, out t) ? t : (DateTime?)null
             let span = When - originTime
             let Epoch = span.HasValue ? span.Value.TotalSeconds : (double?)null
             select new
             {
                 sWhen,
                 When,
                 Epoch
             };

// result.Take(5).ToList()