3

我有一条使用 FileHelpers 写入 CSV 文件的记录。我希望将结构的 DateTime 字段写为 UTC 日期。我目前有以下格式化程序:

[FieldConverter(ConverterKind.Date, "yyyy-MM-dd")]   

我需要做什么才能输出 UTC 日期?

4

3 回答 3

3

医生说:

您可以检查所有支持的格式字符串,检查 MSDN 文档中的 DateTime.ParseExact

所以根据:http: //msdn.microsoft.com/en-us/library/az4se3k1.aspx

[FieldConverter(ConverterKind.Date, "u")]

"u" => "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 它不会将日期转换为 utc,只是格式化它

您仍然需要 DateTime.ToUniversalTime 来转换它。

编辑 如果你有类似的东西:

[FieldConverter(ConverterKind.Date, "ddMMyyyy" )]
public DateTime ShippedDate;

然后添加一个临时 ShippedDateUTC :

public DateTime ShippedDate;

[FieldConverter(ConverterKind.Date, "ddMMyyyy" )]
public DateTime ShippedDateUTC {
  get{ return ShippedDate.ToUniversalTime();}
}
于 2010-10-15T13:29:06.760 回答
3

您可以使用将正确值分配给私有字段的公共设置器来包装转换。例如:

public class OutputRecord
{
    [FieldConverter(ConverterKind.Date, "ddMMyyyy" )]
    private DateTime dateInUtc:

    public void SetDate(DateTime date)
    {
        dateInUtc = date.ToUniversalTime();
    }

}

您还可以使用自定义转换器http://www.filehelpers.com/example_customconv.html

于 2010-10-15T13:53:34.380 回答
0

使用DateTime 类的ToUniversalTime()方法

因此,如果ConverterKind.Date是 DateTime 类型,您的代码应该是

[FieldConverter(ConverterKind.Date.ToUniversalTime(), "yyyy-MM-dd")]
于 2010-10-15T13:15:31.367 回答