简体   繁体   中英

Format DateTime issue for Millisecond level with FileHelpers C#

I need very small help for parsing the date time data from csv file by FileHelpers Library using C# application.

The Date Time data I have used in csv files as = 20160803T0509+0100

I am getting the error as below

ex = {"Error Converting '20160803T0509+0100' to type: 'DateTime'.  There are more chars in the Input String than in the Format string: 'yyyyMMdd HH:mm:ss'"}

I am using the code as below

    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
                [FieldTrim(TrimMode.Both)]
                [FieldConverter(ConverterKind.Date, "yyyyMMdd HH:mm:ss")]

 private DateTime _ShipmentDateTime;
                public DateTime ShipmentDateTime
                {
                    get { return _ShipmentDateTime; }
                    set { _ShipmentDateTime = value; }
                }

You are going to have to do some string manipulation as DateTime.Parse() or DateTimeOffset.Parse() won't understand: "20160803T0509+0100"

you will need to look for the "T" and remove it, count 2 characters on and put a ":" also you will need to find the "+" and count 2 characters and put a ":".

That would get you something like this: "20160803 05:09 +01:00" . If you know that it is formatted as YYYYMMDD in the csv file add "/" at the relevant positions to get: "2016/08/03 05:09 +01:00"

Now, DateTimeOffset.Parse() will understand this string.

public DateTime ShipmentDateTime
 {
   get { return _ShipmentDateTime; }
   set { 
         var dateTimeOffset = DateTimeOffset.Parse(value); //value = "2016/08/03 05:09 +01:00"
         _ShipmentDateTime = dateTimeOffset.UtcDateTime; 
       }
 }

Side Note:

Is there any particular reason you are using Datetime over DateTimeOffset as shipping is multi-time-zone and DateTimeOffset is generally safer to work with. You could always convert to DateTime at a later stage for display purposes, but at least you still have the offest significant figures.

You can use the format yyyyMMddTHHmmzzz . The zzz handles the timezone information. The full attribute you need to use is:

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

The documentation states that " You can find all the supported format strings in the MSDN docs for DateTime.ParseExact " so you can prove the above with a simple app ( DotNetFiddle ):

DateTime d = DateTime.ParseExact("20160803T0509+0100", "yyyyMMddTHHmmzzz", CultureInfo.CurrentCulture);
Console.WriteLine(d);
Console.WriteLine(d.ToString("yyyyMMddTHHmmzzz"));

Which produces (on my UK system)

03/08/2016 05:09:00
20160803T0509+01:00

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