How to validate check datetime input as ISO 8601 - c#

I try to validate an input and then i can get input like that i want to.
Example:
if (string != validate(string))
then not valid
else
then valid
Inputs and expected output
2017-03-17T09:44:18.000+07:00 == valid
2017-03-17 09:44:18 == not valid

To check valid DateTime, you need correct DateTime format (i.e "yyyy-MM-ddTHH:mm:ss.fffzzz") and use DateTime.TryParseExact() to validate your datetime string,
Try below code to validate your datetime string,
public void ValidateDateTimeString(string datetime)
{
DateTime result = new DateTime(); //If Parsing succeed, it will store date in result variable.
if(DateTime.TryParseExact(datetime, "yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
Console.WriteLine("Valid date String");
else
Console.WriteLine("Invalid date string");
}
Try it online

You should be able to use DateTime.TryParseExact. This will return true/false based on whether it parses correctly. You can specify the pattern to match using format parameter.

You could use regex to match the date format you want (take a look at this example as to what your Regex should look like, depending on the format you need).
function Validate(string Input)
{
System.Text.RegularExpressions.Regex MyRegex = new
System.Text.RegularExpressions.Regex("([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))");
return MyRegex.Match(Input).Success // returns true or false
}

Related

I have the following string "12-5" and I'm trying to parse it using TryParse in .NET. It returned true, How to acheive a false for the given string?

When giving "12-5" or "12,5" as an input to DateTime.TryParse in .NET, it is converting it to "12-05-2020" and the return value is true. How is "12-5" equal to "12-05-2020"? In my case, the input string is the user's date of birth and it is a free text as per the requirement and the parsed value "12-05-2020" makes no sense as the date of birth cant be a future date. Is there a way to correct this without using DateTime.Parse or DateTime.ParseExact as they might throw exceptions.
Well, you have 2 tests to perform:
For a valid date syntax (say, bla-bla-bla is not one)
For a valid date value (say, 25-03-2123 is not one)
Let's check for these requirements in one if:
string userInput = "12-05-15"; // 12 May 2015
...
// We can use several formats in one go:
// DateTime.TryParseExact will try formats in the given order
string[] allowedFormats = new string[] {
"d-M-yy", "d-M-yyyy", "MMM d yyyy",
};
if (DateTime.TryParseExact(
userInput.Trim(), // let's tolerate leading/trailing whitespaces
allowedFormats,
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out var result) &&
result <= DateTime.Today &&
result >= DateTime.Today.AddYears(-150)) {
// result is
// 1. Valid date
// 2. At least 150 years ago
// 3. At most today
}
else {
// userInput doesn't meet at least one criterium
}
As #Rafalon suggested, use DateTime.TryParseExact to avoid exceptions and set the format you want.
string dateformat = "12-05";
bool answer = DateTime.TryParseExact(dateformat, "dd-MM-yyyy", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime result);

C# check pattern of a datetime

I have to receive a datetime property through webservice which has two possible formats:
2018-05-14T12:20:45:123+02:00
2018-05-14T12:20:45:123Z
How can I ask to a datetime variable if the pattern is one or another?
yyyy-MM-ddTHH:mm:ss.fffzzz
yyyy-MM-ddTHH:mm:ss.fffZ
You can use TryParseExact which will return bool - true if parse succeed else false:
bool isPattern1 = DateTime.TryParseExact("yourdate string", "yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result1);
bool isPattern2 = DateTime.TryParseExact("yourdate string", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result2);
if(isPattern1)
{
//your code
}
if(isPattern2)
{
//your code
}
OR you can use second overload with string[] as formats parameter if you don't need to actually check which pattern worked, but you need to be sure that string was from this two formats:
var formats = new [] { "yyyy-MM-ddTHH:mm:ss.fffzzz", "yyyy-MM-ddTHH:mm:ss.fffZ" };
bool isParseSucceed = DateTime.TryParseExact("yourdate string", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result);
DateTime haven't got any format. What you call format is a "format of string representation of DateTime".
You can parse both values with DateTime.Parse() or DateTime.TryParse() - they will work for both.
DateTime.Parse("2018-05-14T12:20:45.123+02:00") // [14.05.2018 15:20:45]
DateTime.Parse("2018-05-14T12:20:45.123Z") // [14.05.2018 15:20:45]
To determine wich format you receive from webservice:
if (responseDateTimeString.EndsWith("Z"))
// it's '2018-05-14T12:20:45.123Z' format
else
// it's not '2018-05-14T12:20:45.123Z' format (it's '2018-05-14T12:20:45.123+02:00')

Validation of DateTime Format

I am trying to validate datetime format which user can provide. Here is the sample code ...
DateTime tempDateTime;
string _userFormat = "aa";
string tempDateTime2 = DateTime.Now.ToString(_userFormat);
bool b = DateTime.TryParseExact(tempDateTime2, _userFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateTime);
Console.WriteLine("{0},{1}", tempDateTime, b);
Console.ReadLine();
This returns true (value of b) and valid dateTime (tempDateTime). I was in impression that this will return false because the _userFormat is not valid format. So is there any other way or am i missing something.
Thank you
Since you are calling ToString() with the format aa, which does not represent a valid custom format code, the code it treated as a string literal and you get the string value aa back.
When you then try to parse the "date" using the same format specifier, it sees that the format of the source string matches the format specifier, so it parses it without error. Since neither the source nor format code specifies any viable information about the data/time, a "default" value of DateTime.Now.Date is used.
From MSDN:
If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

DateTime.TryParseExact method for string comparison

Hey how can you do a string comparison match for a given date, DateTime.TryParseExact seems like the sensible option but I am not sure how to construct the arguement in the below method:
public List<Dates> DateEqualToThisDate(string dateentered)
{
List<Dates> date = dates.Where(
n => string.Equals(n.DateAdded,
dateentered,
StringComparison.CurrentCultureIgnoreCase)).ToList();
return hiredate;
}
If you know the format of the date/time exactly (i.e. it never changes, and does not depend on the culture or locale of the user), then you can use DateTime.TryParseExact.
For example:
DateTime result;
if (DateTime.TryParseExact(
str, // The string you want to parse
"dd-MM-yyyy", // The format of the string you want to parse.
CultureInfo.InvariantCulture, // The culture that was used
// to create the date/time notation
DateTimeStyles.None, // Extra flags that control what assumptions
// the parser can make, and where whitespace
// may occur that is ignored.
out result)) // Where the parsed result is stored.
{
// Only when the method returns true did the parsing succeed.
// Therefore it is in an if-statement and at this point
// 'result' contains a valid DateTime.
}
The format string can be a fully specified custom date/time format (such as dd-MM-yyyy), or a general format specifier (such as g). For the latter, the culture matters as to how the date is formatted. For example, in the Netherlands dates are written as 26-07-2012 (dd-MM-yyyy) whereas in the US dates are written as 7/26/2012 (M/d/yyyy).
However, this all only works when your string str contains only the date you want to parse. If you have a bigger string with all sorts of unwanted characters around the date, then you'll have to find the date in there first. This can be done using a regular expression, which is a whole other topic in itself. Some general information about regular expressions (regex) in C# can be found here. A regular expression reference is here. For example, a date similar to d/M/yyyy can be found using the regex \d{1,2}\/\d{1,2}\/\d{4}.
Another way of doing it is to convert your date from string to DateTime. If it is possible I would keep DateAdded as DateTime.
Bellow is a code that runs in LINQPad
public class Dates
{
public string DateAdded { get; set; }
}
List<Dates> dates = new List<Dates> {new Dates {DateAdded = "7/24/2012"}, new Dates {DateAdded = "7/25/2012"}};
void Main()
{
DateEqualToThisDate("7/25/2012").Dump();
}
public List<Dates> DateEqualToThisDate(string anything)
{
var dateToCompare = DateTime.Parse(anything);
List<Dates> hireDates = dates.Where(n => DateTime.Parse(n.DateAdded) == dateToCompare).ToList();
return hireDates;
}

string represents date, and reformat it

The following case:
There is a string that has this format "2012-02-25 07:53:04"
But in the end, i rather want to end up with this format "25-02-2012 07:53:04"
I think i have 2 options. 1 would be to reformat the string and move it all around, but i dont think this is a clean way of doing this.
A other way that i was thinking about is to save the source string to a date parameter, and then write the date parameter back to a string in a certain date format.
But is this even possible to do ?
Do this:
DateTime.Parse("2012-02-25 07:53:04").ToString("dd-MM-yyyy hh:mm:ss");
Keep in mind this isn't culture-aware. And if you do need to store the intermediate result you could do that just as easily:
var myDate = DateTime.Parse("2012-02-25 07:53:04");
var myDateFormatted = myDate.ToString("dd-MM-yyyy hh:mm:ss");
Lastly, check out TryParse() if you can't guarantee the input format will always be valid.
Others have suggested using Parse - but I'd recommend using TryParseExact or ParseExact, also specifying the invariant culture unless you really want to use the current culture. For example:
string input = "2012-02-25 07:53:04";
DateTime dateTime;
if (!DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime))
{
Console.WriteLine("Couldn't parse value");
}
else
{
string formatted = dateTime.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Console.WriteLine("Formatted to: {0}", formatted);
}
Alternatively using Noda Time:
string input = "2012-02-25 07:53:04";
// These can be private static readonly fields. They're thread-safe
var inputPattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyy-MM-dd HH:mm:ss");
var outputPattern = LocalDateTimePattern.CreateWithInvariantInfo("dd-MM-yy HH:mm:ss");
var parsed = inputPattern.Parse(input);
if (!parsed.Success)
{
Console.WriteLine("Couldn't parse value");
}
else
{
string formatted = outputPattern.Format(parsed.Value);
Console.WriteLine("Formatted to: {0}", formatted);
}
Parse as DateTime then reformat it. Be careful: use always an IFormatProvider!
Yes, it is quite possible. All you need to do is use DateTime.Parse to parse the string into a DateTime struct and then use ToString() to write the date back out to another string with the format you want.
You can parse this as a date object and then provide the formatting you want when using the date.ToString method:
date.ToString("dd-MM-yyyy hh:mm:ss");
Yes, you can use custom DateTime format strings to parse and reformat DateTime objects.
DateTime date = DateTime.ParseExact("2012-02-25 07:53:04", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string formattedDated = date.ToString("dd-MM-yyyy HH:mm:ss");

Categories

Resources