FlatFile
FlatFile copied to clipboard
FixedLength with DateTime
I use the Fixed length attributes to define my structure.
I have a given format with yyyyMMdd hh:mm. How can I specify this for a DateTime property? I found no attribute and no sample how to map DateTime types.
I found a possible method how this can be done, see #43. Looks ugly, but it works.
I created a new DateConverter to make this thing work.
I create one layout usign this command:
.WithMember(x => x.DataMaximoAno, c => c.WithLength(8).WithTypeConverter<BDIDateTypeConverter>())
public class BDIDateTypeConverter : ITypeConverter
{
public bool CanConvertFrom(Type type)
{
bool ret = typeof(String) == type;
return ret;
}
public bool CanConvertTo(Type type)
{
bool ret = typeof(System.DateTime) == type;
return ret;
}
public object ConvertFromString(string source)
{
DateTime? newDate = null;
newDate = ParseDateTime(source);
return newDate;
}
public string ConvertToString(object source)
{
string dateFormated = string.Empty;
DateTime? oldDate = (System.DateTime?)source;
if (oldDate.HasValue)
dateFormated = oldDate.Value.ToString("yyyyMMdd");
return dateFormated;
}
private DateTime? ParseDateTime(
string dateToParse,
string[] formats = null,
IFormatProvider provider = null,
DateTimeStyles styles = DateTimeStyles.AssumeLocal)
{
string[] CUSTOM_DATE_FORMATS = new string[]
{
"yyyyMMddTHHmmssZ",
"yyyyMMddTHHmmZ",
"yyyyMMddTHHmmss",
"yyyyMMddTHHmm",
"yyyyMMddHHmmss",
"yyyyMMddHHmm",
"yyyyMMdd",
"yyyy-MM-dd-HH-mm-ss",
"yyyy-MM-dd-HH-mm",
"yyyy-MM-dd",
"MM-dd-yyyy"
};
if (formats == null)
{
formats = CUSTOM_DATE_FORMATS;
}
DateTime validDate;
foreach (var format in formats)
{
if (format.EndsWith("Z"))
{
if (DateTime.TryParseExact(dateToParse, format,
provider,
DateTimeStyles.AssumeUniversal,
out validDate))
{
return validDate;
}
}
else
{
if (DateTime.TryParseExact(dateToParse, format,
provider, styles, out validDate))
{
return validDate;
}
}
}
return null;
}
}
Hello @lw-schick , @pelife I think that it will add this extension in #55
I think a more general useful would to allow you to specify a func that returns a value like Func<string, T> That way you get the input say F and you could do .ConvertValue(input => input == "F") to convert to false with compile time checking. This is what I thought I could do with String Normalizer but that will never work in my use case as I need to convert to multiple characters / value and the column is only 1 character long.