简体   繁体   中英

Parse date with any separator

I have an object that stores info about its content.

var columnType = new ColumnType
    {
        ColumnName = "DateTime D/M/Y",
        ColType = typeof (DateTime),
        Format = "ddMMyyyy HH:mm"
    }

Based on that I need to parse rows before adding them to this column. The problem is that my format doesn't include separators. I want to parse the date no matter what separator.

The standard DateTime.Parse doesn't have a constructor with format, and DateTime.ParseExact expects that the specified format already has separators in it.

I need something that will parse date like that: If my format is ddMMyyyy HH:mm , then:

05.03.2016 04:19 -> parsed

05-03-2016 04:19 -> parsed

05/03/2016 -> parsed (time should be optional)

2016/03/05 04:19 -> error

I tried to do this, but without separators in format it didn't work:

var format = "ddMMyyyy HH:mm";
DateTime.TryParseExact("05.03.2016 04:19", format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime resultValue);

Something like this may work for you. This first snippet doesn't deal with optional time, see below.

char[] separators = { '/', '-', '.', '@', '#' };
string format = "dd?MM?yyyy HH:mm"; // ? replaced with each separator
// Create and populate an array of all acceptable formats
string[] formats = new string[separators.Length];
for (int i = 0; i < separators.Length; i++)
{
    formats[i] = format.Replace('?', separators[i]);
}
DateTime dt;
if (DateTime.TryParseExact("05#12#2017 15:36", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    // Use dt
}
else
{
    // No format matched
}

This works by using DateTime.TryParseExact that accepts a string array of formats, rather than one single format. This works because:

The format of the string representation must match at least one of the specified formats exactly.

It must be noted that all the separators must be the same in the input string, no mix and match.

For optional time you could add other formats that do not include HH:mm . For example:

...
string formatWithTime = "dd?MM?yyyy HH:mm";
string formatWithoutTime = "dd?MM?yyyy";
List<string> f = new List<string>();
foreach (char c in separators)
{
    f.Add(formatWithTime.Replace('?', c));
    f.Add(formatWithoutTime.Replace('?', c));
}
string[] formats = f.ToArray();
...

DateTime.Parse works with the samples depending on the IFormatProvider :

var ci = new CultureInfo("pl");
var d1 = DateTime.Parse("05.03.2016 04:19", ci);
var d2 = DateTime.Parse("05-03-2016 04:19", ci);
var d3 = DateTime.Parse("05/03/2016"      , ci);
var d4 = DateTime.Parse("2016/03/05 04:19", ci);

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