How to validate if string is a date in specific format?

Ask general questions here.
reutH
Posts: 3
Joined: Mon May 15, 2017 7:38 am

How to validate if string is a date in specific format?

Post by reutH » Mon Jul 03, 2017 1:15 pm

I have list of dates formats. I want to verify that in my app, specific string is changed according the format selected in settings.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 3932
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: How to validate if string is a date in specific format?

Post by odklizec » Mon Jul 03, 2017 1:41 pm

Hi,

I would try something like this:

Code: Select all

		using System.Globalization;
		/// <summary>
		/// validate date format
		/// </summary>
		/// <param name="dateString">date string</param>
		/// <param name="dateFormatString">expected date format</param>
		public void ValidateDateFormat(string dateString, string dateFormatString)
		{
			try
			{
				System.DateTime dt = System.DateTime.ParseExact(dateString, dateFormatString, System.Globalization.CultureInfo.InvariantCulture);
			}
			catch
			{
				Report.Log(ReportLevel.Failure, "Validated date in incorrect format. \r\nValidated date: " + dateString + "\r\nValidated date format: " + dateFormatString);
			}
		}
Simply, pass the date and expected format to above method and if date is incorrect in format, ParseExact fails and so it logs failure in Ranorex report. Hope this helps?
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration