Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
FunLovinCoder Avatar asked Dec 06 '25 07:12

FunLovinCoder


2 Answers

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();}
}
like image 97
oleveau Avatar answered Dec 07 '25 21:12

oleveau


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

like image 37
Marcos Meli Avatar answered Dec 07 '25 20:12

Marcos Meli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!