将日期时间字符串列表转换为日期时间值列表
本文关键字:列表 时间 日期 字符串 转换 | 更新日期: 2023-09-27 18:15:13
我是c#新手。使用SharpDevelop程序。我可以在"for"循环中转换ISO 8601 DateTime值。我确信"记录"的ToList方法将允许我将所有字符串条目转换为日期时间值,但我无法到达那里。请帮助。
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 );
}
}
要从某种类型的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();
您可以使用LINQ来实现
var l = records
.Select(x=>System.DateTime.ParseExact(x.TimeWhen, myFormat, null))
.Select(x=>x.Subtract(originTime))
.Select(x=>mySpan.TotalSeconds)
.ToList();
除了使用linq,您还可以使用扩展方法:
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());
从签名你的CsvReader返回一个IEnumerable。是否将其转换为列表取决于您。对于日期时间转换,我将使用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()