C# check pattern of a datetime - c#

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')

Related

Use DateTime.TryParseExact to format date string and ignore time

I want to parse string date to DateTime but ignoring time.
My expected date format is M/d/yyyy which is 3/29/2018 (without leading zero).
The thing is string can be with or without time part and time can have different formats that I will not predict.
var inputDateString = "12/31/2017 12:00:00 AM" // false, but I want to parse
var inputDateString = "12/31/2017" // true
DateTime.TryParseExact(inputDateString, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate);
Is there any way to parse date string having only specific date format and ignore time?
There is an overload to TryParseExact that allows you to pass in multiple formats. If you know in advance which formats to expect, you can use this overload:
void Main()
{
string[] validFormats = {"M/d/yyyy", "M/d/yyyy hh:mm:ss tt"};
var inputDateString1 = "12/31/2017 12:00:00 AM"; // false, but I want to parse
var inputDateString2 = "12/31/2017"; // true
DateTime.TryParseExact(inputDateString1, validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt1);
DateTime.TryParseExact(inputDateString2, validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt2);
}
You can then get only the date portion using the Date property.
You could strip the time part from the input string, or parse the full input, using only the .Datepart.
var parsedDate = DateTime.MinValue;
var inputDateString = "12/31/2017 12:00:00 AM"; // false, but I want to parse
// option 1: use only the date part
if (DateTime.TryParseExact((inputDateString ?? "").Split(' ')[0] , "M/d/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
Console.WriteLine(parsedDate);
// option 2: use the full input, but ignore the time
if (DateTime.TryParseExact(inputDateString, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
Console.WriteLine(parsedDate.Date);
Personally, I would go with the first option.
If you always want to only parse the Date portion that can be done by explicitly ensuring the string is only 10 characters in length. This is a somewhat convoluted example but you can strip out what you don't need, you'll get the idea:
var inputDateString = "12/31/2017 12:00:00 AM";
string datePortion = string.Empty;
DateTime dt;
if (inputDateString.Length>10)
{
// take first 10 characters of inputDateString
datePortion = inputDateString.Substring(0, Math.Min(inputDateString.Length, 10));
}
else if (inputDateString.Length==10)
{
// inputDateString is already 10 characters
datePortion = inputDateString;
}
else
{
// inputDateString is less than 10 characters, no date found, do nothing.
}
if(!DateTime.TryParse(datePortion, out dt))
{
// handle error that occurred,
}
else
{
// parse was successful, carry on.
}

Convert a string to DateTime in C#

I am trying to convert a string to a DateTime for some hours now,
The string looks like this
"20140519-140324" and I know its in UTC
I've allready tried this
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
StartTime.Text = ourDateTime.ToString("g");
and this
DateTime ourDateTime= DateTime.ParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
StartTime.Text = ourDateTime.ToString("g");
but none of these work. What I am not doing properly?
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your example, they are not. Use yyyyMMdd-HHmmss custom format instead which exactly matches with your string.
Here an example on LINQPad;
string s = "20140519-140324";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
dt.Dump();
}
Here a demonstration.
Your DateTime.ParseExact example also won't work because of the same reason.
For more information;
Custom Date and Time Format Strings
You are using the wrong format in the TryParseExact method.
the format parameter should be an indicator to the format of the input string.
therefor you need to do this:
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
if(success) {
StartTime.Text = ourDateTime.ToString("g");
}

String based DateTime format or pattern check

I have a datetime string.
string strDate = "20140424_18255375";
How to verify the datetime is having in this format YYYYMMDD_HHmmssff
I tried:
bool isTrue = DateTime.TryParseExact(strDate, "YYYYMMDD_HHmmssff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Please help if there is a better way to verify the datetimes with RegEx or any normal way.
Using TryParseExact is the right way to go about it, but you need to use the right format specifiers. In this case, I think you want:
bool valid = DateTime.TryParseExact(strDate, "yyyyMMdd_HHmmssff",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Note the use of yyyy instead of YYYY and dd instead of DD. Format specifiers are case-sensitive.
Try this
public override bool IsValid(object value)
{
var dateString = value as string;
if (string.IsNullOrWhiteSpace(dateString))
{
return true; // Not our problem
}
DateTime result;
var success = DateTime.TryParse(dateString, out result);
return success;
}
just add your format for date.

String to Date parsing

I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);

Convert a string to a date in .net

I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
or
DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
More info in the MSDN documentation on ParseExact and TryParseExact.
you could try also TryParseExact for set exact format.
method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx
e.g.
DateTime outDt;
bool blnYYYMMDD =
DateTime.TryParseExact(yourString,"yyyyMMdd"
,CultureInfo.CurrentCulture,DateTimeStyles.None
, out outDt);
I hope i help you.
DateTime.TryParse method
You can also do Convert.ToDateTime
not sure the advantages of either
Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.
Regards...
You can use the TryParse method to check validity and parse at same time.
DateTime output;
string input = "09/23/2008";
if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
{
//handle valid date
}
else
{
//handle invalid date
}

Categories

Resources