Is It Possible in C# to Check If a Given Date Format String Contains Just a Date Format or Time Format

Is it possible in C# to check if a given date format string contains just a date format or time format?

I would go with something along the lines of:

[Flags]
public enum DateFormatStringKind
{
HasNone = 0,
HasDate = 1 << 0,
HasTime = 1 << 1,
HasBoth = HasDate | HasTime
}

public static DateFormatStringKind DescribeFormatString(string s, IFormatProvider provider)
{
DateTime d = new DateTime(2, 2, 2, 1, 1, 1, 1); // DateTime will all non-default values
DateTime d2 = DateTime.ParseExact(d.ToString(s, provider), s, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

DateFormatStringKind result = DateFormatStringKind.HasNone;

if (d2.Date.Ticks != 0)
result |= DateFormatStringKind.HasDate;

if (d2.TimeOfDay != TimeSpan.Zero)
result |= DateFormatStringKind.HasTime;

return result;
}
var culture = System.Globalization.CultureInfo.InvariantCulture;

Console.WriteLine(DescribeFormatString("dd/MM/yyyy", culture));
Console.WriteLine(DescribeFormatString("yyyy MM yyyy", culture));
Console.WriteLine(DescribeFormatString("h:mmtt", culture));
Console.WriteLine(DescribeFormatString("dd h:mmtt", culture));
Console.WriteLine(DescribeFormatString("'literal'", culture));
HasDate
HasDate
HasTime
HasBoth
HasNone

It converts a date with all non-default fields into a string using the format string and then back using the same format string, and then checks what fields survived the conversion.

If there was no date component in the pattern, the "date" part will be 0001-01-01, which is the zero date (zero ticks from the point 0). The NoCurrentDateDefault flag ensures that the current date is not used instead.

If there was no time component in the pattern, the time will reset to midnight (TimeSpan.Zero from midnight).

If there was at least one component of the date pattern (either year, month or day), the respective field will become 2, which is greater than the default 1 for the date fields, so it will be detected regardless of what component that was.

If there was at least one component in the time pattern (hours, minutes, seconds, milliseconds), it will become 1, which is greater than the default 0 for the time fields, so it will again be detected regardless of what component it was.

Checking Date format from a string in C#

string inputString = "2000-02-02";
DateTime dDate;

if (DateTime.TryParse(inputString, out dDate))
{
String.Format("{0:d/MM/yyyy}", dDate);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}

Check if a string is a valid date using DateTime.TryParse

If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

DateTime.TryParse

This method tries to ignore unrecognized data, if possible, and
fills in missing month, day, and year information with the current
date. If s contains only a date and no time, this method assumes the
time is 12:00 midnight. If s includes a date component with a
two-digit year, it is converted to a year in the current culture's
current calendar based on the value of the Calendar.TwoDigitYearMax
property. Any leading, inner, or trailing white space character in s
is ignored.

If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;

foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

check if date time string contains time

The date time components TimeOfDay is what you need.

MSDN says "Unlike the Date property, which returns a DateTime value that represents a date without its time component, the TimeOfDay property returns a TimeSpan value that represents a DateTime value's time component."

Here is an example with consideration of all your scenarios.

Since you are sure of the format you can use DateTime.Parse else please use DateTime.TryParse

var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00");
var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00");
var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34");
var dateTime4 = System.DateTime.Parse("02/20/10");

if (dateTime1.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("1980/10/11 12:00:00 - does not have Time");
} else {
Console.WriteLine("1980/10/11 12:00:00 - has Time");
}

if (dateTime2.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time");
} else {
Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time");
}

if (dateTime3.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("10/02/10 03:30:34 - does not have Time");
} else {
Console.WriteLine("10/02/10 03:30:34 - Has Time");
}

if (dateTime4.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("02/20/10 - does not have Time");
} else {
Console.WriteLine("02/20/10 - Has Time");
}

Check if a string is in a specific date format

You can solve this with a couple calls to TryParseExact:

public static DateTime ParseDate(string input)
{
DateTime result;

if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;

throw new FormatException();
}

Give it a quick test:

public static void Main()
{
string[] tests = new string[] { "2018-06-29", "29-06-2018","Invalid" };

foreach (var t in tests)
{
var result = ParseDate(t);
Console.WriteLine( "Year: {0} Month: {1} Day: {2}", result.Year, result.Month, result.Day );
}
}

Output:

Year: 2018  Month: 6  Day: 29
Year: 2018 Month: 6 Day: 29
Run-time exception (line 18): One of the identified items was in an invalid format.

Sample code on DotNetFiddle

Finding if a string contains a date and time

If the format of the date has been defined, you can use Regex to solve it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegTest
{
class Program
{
static void Main(string[] args)
{
string testDate = "3214312402-17-2013143214214";
Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}");
Match mat = rgx.Match(testDate);
Console.WriteLine(mat.ToString());
Console.ReadLine();
}
}
}

Check if given string is valid format string for converting DateTime

This kind of depends on what you mean by "valid" and how important you think the "only DateTime, nothing else" restriction is to you.

Here are a few rules that we can use to test format strings, with some express limitations:

  1. Must be suitable for passing to DateTime.ToString(string format) to convert a DateTime value to string.

  2. Must be usable to parse the output of rule 1 into a valid DateTime value.

  3. The output of rule 2 must not contain a time portion.

  4. Optionally, the output of rule 2 should be the same as the input within a defined range of accuracy.

These will be good enough for many uses, as long as you are expecting that the output be a fully specified date. Year, month and day must be specified. Here's some code to test against those rules:

static System.Globalization.CultureInfo DateTimeProvider = System.Globalization.CultureInfo.InvariantCulture;
const System.Globalization.DateTimeStyles ParseExactStyle = System.Globalization.DateTimeStyles.None;
static DateTime[] DateSamples = new[]
{
DateTime.Now,
DateTime.Today,
DateTime.Today.AddDays(1 - DateTime.Today.Day),
DateTime.Parse("10-Jan-2000"),
DateTime.Parse("01-Oct-1990"),
DateTime.Parse("13-Feb-1901")
};

public static bool IsValidDateFormat(string format, out string result)
{
var maxDifference = TimeSpan.FromDays(1);
foreach (var sample in DateSamples)
{
// Rule 1: Must be suitable for '.ToString(...)'
string sampleString;
try
{
sampleString = sample.ToString(format);
}
catch (FormatException e)
{
result = $"Failed rule 1: {e.Message}";
return false;
}

// Rule 2: Must be able to parse the produced string
if (!DateTime.TryParseExact(sampleString, format, DateTimeProvider, ParseExactStyle, out var parsed))
{
result = $"Failed rule 2: does not parse it's own output. '{sampleString}'";
return false;
}

// Rule 3: No time values.
if (parsed != parsed.Date)
{
result = $"Failed rule 3: No time values. '{sampleString}' => #{parsed}#";
return false;
}

// Rule 4: Difference must be less than maxDifference
TimeSpan difference = sample < parsed ? parsed - sample : sample - parsed;
if (difference >= maxDifference)
{
result = $"Failed rule 4: difference '{difference}' too large.";
return false;
}
}

result = "OK";
return true;
}

(This sets the result out parameter to a description of why the format string failed, or OK if it passed, but you might prefer to return a simple enum value.)

This validates on all sorts of weird formats, including those with extra non-contextual - or at least non-time - characters. The samples include a few tests against time values, order reversal and so on.

There are some limitations however:

  • TryParseExact does not work with standard format strings like d, 'F', etc.
  • Nor does it work with the 3+ digit year format (yyy) and other stretching formats.
  • The samples include a test that prevents 2-digit years being used.

In short, it's good enough for simple work. You can trim it back a bit.

How to check date format c#

One of the overloads of TryParseExact accepts as its second parameter an array of strings. It won't tell you exactly which format was used, however. If you really do need that information, then yes, you're just going to have to run the one-format TryParseExact with each format you want, and see which one works.

And, of course, you'll need to make sure that all the formats you allow are unambiguous as to which parts are day, month, and year, or else you might parse 01/02/03 as any of six possible dates.

How to check if date is in correct format i.e. yyyy-mmm-dd?

Use DateTime.TryParseExact

DateTime dt;
string[] formats = { "yyyy-MMM-dd"};
if (!DateTime.TryParseExact(dateValue, formats,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}

How to validate if a "date and time" string only has a time?

You can use DateTime.TryParseExact.



Related Topics



Leave a reply



Submit