3

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?

FunLovinCoder
  • 7,597
  • 11
  • 46
  • 57

3 Answers3

3

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();}
}
oleveau
  • 200
  • 1
  • 13
3

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

Marcos Meli
  • 3,468
  • 24
  • 29
0

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")]
Lorenzo
  • 29,081
  • 49
  • 125
  • 222