简体   繁体   中英

Format DateTime to UTC with FileHelpers

I have a record that I write out to a CSV file using FileHelpers. I want the DateTime fields of the structure to be written out as the UTC date. I currently have the following formatter:

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

What do I need to do to get it to output the UTC date?

The doc says :

You can check all the supported format strings check the MSDN docs for DateTime.ParseExact

So according to : http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

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

"u" => "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" It doesn't convert the date to utc, just format it

You still need DateTime.ToUniversalTime to convert it.

Edit If you have something like :

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

Then add a temp ShippedDateUTC :

public DateTime ShippedDate;

[FieldConverter(ConverterKind.Date, "ddMMyyyy" )]
public DateTime ShippedDateUTC {
  get{ return ShippedDate.ToUniversalTime();}
}

You can wrap the transformation with a public setter that assigns the right value to a private field. For example:

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

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

}

You can also use a custom converter http://www.filehelpers.com/example_customconv.html

Use the ToUniversalTime() method of the DateTime class

So, if the ConverterKind.Date is of type DateTime your code should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM