String based DateTime format or pattern check - c#

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.

Related

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

C#: Is this possible to convert 24hrs format string Datetime to 12hrs AM/PM dateformat (again in string only)

I have a date/time return from a C# method is in string,
string dateTime = "2018-6-18 20:50:35"
Now I would like to convert this into another string representation like,
string convertDT = "2018-6-18 08:50:35 PM"
Is this possible?
Seems like I can do something like,
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
but not working. Suggestion please!
Just parse the string into a new DateTime object and then call ToString() with the right formats:
string dateTime = "2018-6-18 20:50:35";
DateTime parsedDateTime;
if(DateTime.TryParse(dateTime, out parsedDateTime))
{
return parsedDateTime.ToString("yyyy-M-d hh:mm tt");
}
The benefit of my answer is that it contains validation (DateTime.TryParse()), it results in a couple extra lines of code but you can now accept all input and not worry about an exception being thrown.
Even better would be to refactor this logic into its own method that you can re-use:
public static bool TryChangeDateTimeFormat(string inputDateString, string outputFormat, out string outputDateString)
{
DateTime parsedDateTime;
if(DateTime.TryParse(inputDateString, out parsedDateTime))
{
outputDateString = parsedDateTime.ToString(outputFormat);
return true;
}
outputDateString = string.Empty;
return false;
}
This returns a bool of whether or not the conversion was successful and the out variable will be modified depending on the result.
Fiddle here
Without adding any validation,
var string24h = "2018-6-18 20:50:35";
var dateTime = DateTime.Parse(string24h);
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
Use DateTime.ParseExact and then ToString
Sure, you can use the DateTime class to parse the original string and then output a differently formatted string for the same date:
string result = DateTime.Parse(dateTime).ToString("h:mm tt", CultureInfo.InvariantCulture);
var dateTime = "2018-6-18 20:50:35";
var dt = Convert.ToDateTime(dateTime);
var amPmDateTime = dt.ToString(#"yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
To give you exactly your format you would use
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-MM-dd hh:mm:ss tt");
You can change the format between the quotes however you would like. For example yyyy/MM/dd or something. Just remember MM is 2 spots for months and mm is 2 spots for minutes.
So if you put
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-mm-dd hh:mm:ss tt");
You are going to get year - minutes - days.

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");
}

Check several date formats using DateTime.TryParse()

I'm using a method to validate textboxes.
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Today;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text, out value))
{
return false;
}
}
return true;
}
I want to check the format too. It requires mm/dd/yyyy, but want it to be dd/mm/yyyy
Try DateTime.TryParseExact
DateTime dt;
DateTime.TryParseExact(textBox.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
If you want to check multiple formats as you updated in your question then you can do using another overload method of TryParseExact which takes format parameter as array of string.
string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy" };
DateTime.TryParseExact(txtBox.Text,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out value));
Please take care of format string. As you have mentioned format as dd/mm/yyyy. Here mm represents the minute not the month. Use MM for the month representation.
DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt))
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Now;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text,"dd/mm/yyyy",new CultureInfo("en-US"),
DateTimeStyles.None out value))
{
return false;
}
}
return true;
}
Try using TryParseExact
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. The method returns a value that indicates whether the conversion succeeded.
DateTime.TryParseExact(DateValue,
"dd/mm/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out outDatetime);
Use TryParseExact instead which is also faster.
Example:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string dateString = "27/05/2012"; // <-- Valid
string dtformat = "dd/mm/yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, dtformat, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
}
}

Better way to Select & Read Date in dd/mm/yy format?

In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format.
I use to change the culture info to UK format. So that the date will be selected from SQL server as in dd/mm/yy format.
But I know it's not good to play with CultureInfo. Even though I used like the following manner.
Any other better Ideas for me?
Sub Form_Load()
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)
End Sub
Any other better Ideas for me? Thanks for the Ideas.
Thanks & Regards.
From DateTime to string:
string s = DateTime.Today.ToString("dd/MM/yyyy");
From string to DateTime:
DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
In C# you could get the date string in desired format like,
string date = DateTime.Now.ToString("dd/MM/yyyy");
If you want to get DateTime object from string value representing DateTime in specific culture, you can do
DateTime dt = new DateTime();
DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
System.Globalization.DateTimeStyles.None, out dt);
DateTime --> String
DateTime.Now.ToString( new CultureInfo("fr-FR", false) );
String --> DateTime:
The preferred method would probably be DateTime.Parse()
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.
You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:
DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);
This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.
You can use DateTime.TryParse to parse the date...
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
And even use an IFormatProvider to help TryParse work out the format.
CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}

Categories

Resources