views:

37

answers:

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?

+1  A: 

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
Unfortunately, ConverterKind.Date is not of type DateTime.
swisstony
+1  A: 

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();}
}
olifozzy
Thanks, but it gives Attribute 'FieldConverter' is not valid on this declaration type. It is only valid on 'field' declarations.
swisstony
I just used the ToUniversalTime() before writing the record and that worked.
swisstony
+1  A: 

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

MarcosMeli
Thanks MarcosMeli
swisstony