Webtest - Using Dates as Context Parameters - c#

I've created a webtest and have a CSV data source that contains a column with a list of short dates (MM/dd/yyyy)
I need to manipulate the parameter due to part of the web page I'm testing has a form parameter that needs it to be formatted as yyyyMMdd
When the date that is captured from the data source (ex: 02/12/2016), I noticed in the Context tab of my test run that the format to "2/12/2016 12:00:00 AM"
I've created a Request plug-in and added the following code:
public override void PreRequest(object sender, PreRequestEventArgs e)
{
base.PreRequest(sender e)
string CSVDate = e.WebTest.Context["<datasource date column>"].ToString();
DateTime dt = DateTime.ParseExact(CSVDate, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
e.WebTest.Context.Add("NewDate", dt.ToString("yyyyMMdd"));
}
This generates a String was not recognized as a valid DateTime error. I tried changing the format to MM/dd/yyyy, but I encountered the same error.
Does anyone know how the correct DateTime format I should be using?

The date-time as shown in the context is 2/12/2016 12:00:00 AM. This has only one digit for the month whereas the format specifier has MM which wants two digits. The date-time also contains the letters AM that are not matched by the format.
Modifying the format to be M/dd/yyyy HH:mm:ss matches the date-time 2/12/2016 12:00:00, but does not match the AM part. In theory the tt format specifier should match this, but it did not work for me.
Rather than using ParseExact you can use Parse and it works out the correct format. Using the following worked on the date-time string provided:
DateTime dt1 = DateTime.Parse(CSVDate, new System.Globalization.CultureInfo("en-US"));
The CultureInfo is needed because the input date has the month and the days the wrong way around.
However, the real problem is in the way CSV files are handled by the web test. It appears to read them using the same logic as Microsoft Excel uses when reading CSVs. Namely, if it looks like a date then convert it to a date. So any string matching dd/dd/dddd (where d is a digit) might be connverted to a date. (E.g. 15/15/2017 will not be converted because 15 is not a month number.) I recommend rewriting the CSV to format the input date differently, use something that Excel would not treat as a date. One option is to have the date in three columns of the CSV, so have explicit day,monthandyearcolumns. Another option is to add non-date characters to the string and format it correctly, eg asz20160212and then remove thezwithin the web test. Generally, I would advise to avoid the conversion of string toDateTime` then another conversion to a different string.

Related

Parse a date from an export of a lotus notes base

In a C# application, I have to parse an xml file which is an export of a lotus notes database.
The exports contains dates in this format :
<noteinfo noteid='6706' unid='6B6A3ADD41061773C12580F2004E8EB3' sequence='6'>
<created>
<datetime dst='true'>20170329T161803,39+02</datetime>
</created>
<modified>
<datetime>20171108T100439,39+01</datetime>
</modified>
<revised>
<datetime>20171108T100439,38+01</datetime>
</revised>
<lastaccessed>
<datetime>20171108T100439,38+01</datetime>
</lastaccessed>
<addedtofile>
<datetime dst='true'>20170329T163711,21+02</datetime>
</addedtofile>
</noteinfo>
I have to extract these dates into a .Net Datetime value.
However, I don't get what's this format. Trying to parse the date fails:
var created = DateTime.Parse("20170329T161803,39+02");
Throws
String was not recognized as a valid DateTime
How to parse this date format ?
The first part of the date, before the comma, is obvious. The second part is less. +02 probably match the GMT+02 timezone, but I don't get the 39
PS: I don't have control on the exports
Assuming ,39 are the milliseconds
var created = DateTime.ParseExact("20170329T161803,38+02", "yyyyMMddTHHmmss,ffz", CultureInfo.InvariantCulture);
Reference: DateTime.ParseExact
Try
var created = DateTime.ParseExact("20170329T161803,39+02".Remove(15), "yyyyMMdd'T'HHmmss",CultureInfo.InvariantCulture);
I'm not sure what the ,39+02 is in terms of a time - zone perhaps? I trimmed it off, but if you can describe what it is maybe it can be parsed
Edit:
Assuming that's milliseconds and timezone:
var created = DateTime.ParseExact("20170329T161803,39+02", "yyyyMMdd'T'HHmmss','ffz",CultureInfo.InvariantCulture);

DateTime.Now giving different formats in the same machine

I have a windows service application in which I am getting the current date and time using DateTime.Now.ToString(), which returns '04-05-2018 05:50:12'.
But I tried the same in a sample console application, but it returns the date in a different format as '5/4/2018 5:51:32 AM'
Both these machines are being executed in the same machine. Can some one let me know why is there a date format difference in these applications?
The DateTime.ToString() formats the DateTime according to current culture. As Written in the Documentation
Converts the value of the current DateTime object to its equivalent
string representation using the formatting conventions of the current
culture.(Overrides ValueType.ToString().)
If you want the same string you should instead use the DateTime.ToString(string) overload and provide the exact format which you want.
The ToString(String) method returns the string representation of a
date and time value in a specific format that uses the formatting
conventions of the current culture; for more information, see
CultureInfo.CurrentCulture.
The format parameter should contain either a single format specifier
character (see Standard Date and Time Format Strings) or a custom
format pattern (see Custom Date and Time Format Strings) that defines
the format of the returned string. If format is null or an empty
string, the general format specifier, 'G', is used.
Some uses of this method include:
Getting a string that displays the date and time in the current
culture’s short date and time format. To do this, you use the “G”
format specifier.
Getting a string that contains only the month and year. To do this,
you use the “MM/yyyy” format string. The format string uses the
current culture’s date separator.
Getting a string that contains the date and time in a specific format.
For example, the “MM/dd/yyyyHH:mm” format string displays the date and
time string in a fixed format such as “19//03//2013 18:06". The format
string uses “/” as a fixed date separator regardless of
culture-specific settings.
Getting a date in a condensed format that could be used for
serializing a date string. For example, the "yyyyMMdd" format string
displays a four-digit year followed by a two-digit month and a
two-digit day with no date separator.

Convert date in string to DateTime with same format

I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

DateTime problem when day <= 12

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:
I have a bunch of date strings in cells that I'm pulling out such as:
03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.
While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.
For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00"
The others are all read and nicely provide me with a simple string of "27/05/2011".
I'm getting this info from Excel, using
((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()
If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.
If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.
Example:
var dateString = "03/05/2011";
var format = "dd/MM/yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
More information on custom Date and Time format strings can be found here.
EDIT: Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:
var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);
DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information.
The format of the string representation must match the specified format exactly.
String dateString = "15/06/2008";
String format = "dd/MM/yyyy";
DateTime result =
DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
That sounds like a localization problem. Try setting your locale implicititly. For example in WPF application it's something like:
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
I have a bunch of date strings in cells that I'm pulling out such as:
No, you don't. You have a mix of strings that look like dates and dates that look like strings. This is an Excel issue, not a C# issue.
Not sure if you are creating the spreadsheet, or if you are getting it from somewhere else. But it the problem is that Excel attempt to parse text as it is entered in the cell. In this case, it is making some wrong decisions about the dates it finds.
If you enter a date like "03/05/2011", Excel will (incorrectly) parse it as March 5th, 2011, and store that as a numeric date code (40607). It then applies a date formatting to the cell (it uses m/d/yyyy on my machine).
If you enter a date like "31/05/2011", Excel can't parse it as a date, and it stores it as text.
To prove this, select the cells and go to Edit > Clear > Formats. All the "bad dates" will just show as numbers, all the rest will stay looking like dates.
You have a few choices:
Fix the data before its entered into Excel (prepend everything with a ' so its all entered as text, or make sure to create the spreadsheet on a machine that has the right date settings.)
Don't use the .Value.ToString() from Excel, just use .Text. This will ignore the bad parsing that Excel did, and should give you a consistent text value (from both types) that you can ParseExact with C#, per the other answers.
(2) is a lot easier, and if the spreadsheets already exist, may be your only choice.
The problem is because your Dates are being read as american culture or similar.
If you use the following you can specify the format you expect your dates to be in:use
DateTime result;
if(DateTime.TryParseExact("dd/MM/yyyy", out result))
{
// Got an English date
}

String was not recognized as a valid DateTime - when string format is different from system datetime format

My system short date time format is d/M/yyyy. I'm passing "03/29/2011 02:38:18 PM", so it is giving error "String was not recognized as a valid DateTime"
DateTime.Parse("03/29/2011 02:38:18 PM")
If date time format of machine is set to m/d/yyyy, it works perfectly.
Edit:
My application is a winform application, it contains a data gridview, this grid view contains a custom DateTime control (columns), which is created by other developer.
This error is occurring when I try to change value of this datetime column in grid. VS debugger is not catching the exception, so I'm not able to find location where I should try fixing it.
Thanks
According to the format d/M/yyyy, 03/29/2011 would amount to month number 29 that does obviously not exist.
The other format has day and month switched, and the string then represents 29. March which is a perfectly valid date.
From MSDN:
Important Because the Parse(String)
method tries to parse the string
representation of a date and time
using the formatting rules of the
current culture, trying to parse a
particular string across different
cultures can either fail or return
different results. If a specific date
and time format will be parsed across
different locales, use the
DateTime.Parse(String,
IFormatProvider) method or one of the
overloads of the ParseExact method and
provide a format specifier.
Yes, well, the DateTime.Parse function uses the system format to parse the date, unless you provide a FormatProvider. Obviously in case of d/m/yyyy there is no month 29 so the parsing fails
Use DateTime.ParseExact() instead. You can specify exactly how to parse the date if you know what the string looks like going into the function by passing in the correct FormatString. If the standard DateTime Format Strings don't work, you can use a custom DateTime Format String.
Use DateTime.ParseExact to parse datetime from string
Example:
DateTime.ParseExact("2001-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
You could try to change the culture information, so your input matches the format of the system.
So try to add this in the web.config:
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" />
You can find the answer here: String was not recognized as a valid DateTime " format dd/MM/yyyy"
You can parse the Date with a corresponding CultureInfo, which defines the date format and the order of the date parts (Month,Day,Year) or (Day,Month,Year).
Or you could use the ParseExact and give it a format string as described in the answer above.
See "convert Different formate of DateTime to specific String format in c#"
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

Categories

Resources