我想在读取日期时间时采用特定的时区(EST),然后转换为UTC。
我尝试过:
csvPropertyMap.TypeConverterOption(DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);
但是由于我的代码在本地UTC的云中运行,所以它不起作用。
是否可以在列映射中配置TimeZoneInfo?
答案 0 :(得分:1)
如果您要假设DateTime
值位于特定时区,然后将其转换为UTC,则此方法应该起作用。
static void Main(string[] args)
{
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
using (CsvReader csv = new CsvReader(reader))
{
writer.WriteLine("Id,Name,FooDate");
writer.WriteLine("1,Test,04/19/2019 05:42:00");
writer.Flush();
stream.Position = 0;
var easternStandardTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
csv.Configuration.TypeConverterCache.RemoveConverter<DateTime>();
csv.Configuration.TypeConverterCache.AddConverter<DateTime>(new TimeZonetoUtcConverter(easternStandardTimeZone));
var records = csv.GetRecords<Foo>().ToList();
Console.ReadKey();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime FooDate { get; set; }
}
public class TimeZonetoUtcConverter: DateTimeConverter
{
private readonly TimeZoneInfo timeZoneInfo;
public TimeZonetoUtcConverter(TimeZoneInfo timeZoneInfo)
{
this.timeZoneInfo = timeZoneInfo;
}
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
var parsedDate = base.ConvertFromString(text, row, memberMapData);
return TimeZoneInfo.ConvertTimeToUtc((DateTime)parsedDate, timeZoneInfo);
}
}