Why is NUnit Framework throwing DateTime AssertionException? - c#

I'm trying to format a DateTime, but not change the property to a type of string.
My property is as follows DateTime DateApplicationReceived = FormatDateTime();
I have made a small function to do so which allows me to parse my string into a type of DateTime.
private static DateTime FormatDateTime()
{
var format = DateTime.UtcNow.ToString("G");
var dateTime = DateTime.Parse(format);
return dateTime;
}
Let's say the date & time is now: 16/01/2019 15:30:00. I use NUnit to test that my function works by doing the following assert:
public void ConvertsTime()
{
var sut = DateApplicationReceived;
Assert.That(sut, Is.EqualTo("16/01/2019 15:30:00"));
}
My test fails. The expected result ignores the format (of "G") and displays it to a different culture 2019-01/16.
Debug info:
Why does it do this? I'm explicity giving it a format & changing the culture variant doesn't seem to have any effect.

The DateTime object has no format.
So your code here is useless:
var format = DateTime.UtcNow.ToString("G");
var dateTime = DateTime.Parse(format);
This is fully equivalent to
var dateTime = DateTime.UtcNow;
In your unit test, you should compare either a DateTime with a DateTime, or a string with a string. Currently, you are comparing a DateTime with a string.
So you should change your code to:
Assert.That(sut.ToString("G"), Is.EqualTo("16/01/2019 15:30:00"));
or
Assert.That(sut, Is.EqualTo(DateTime.Parse("16/01/2019 15:30:00")));

Related

c# unit test datetime against string

I am doing a unit test for datetime and it fails because Test Name:
GetDateTime2 Result Message: Assert.AreEqual failed.
Expected:<28/05/2017 20:00:00 (System.String)>. Actual:<28/05/2017
20:00:00 (System.DateTime)>.
Is there any way of comparing the string against the datetime of do i have to change the properties of string date and string time?
public void GetDateTime()
{
FootballEvent football = new FootballEvent();
football.Time = "20:00:00";
football.Date = "28/05/2017";
var footballtime = football.GetDateTime();
var expected = "28/05/2017 20:00:00";
Assert.AreEqual(expected, footballtime);
}
as some people have stated within the comments why not just make a DateTime object then compare them?
Example:
var footballtime = football.GetDateTime();
var expected = "28/05/2017 20:00:00";
DateTime expectedDate = DateTime.Parse(expected);
Assert.AreEqual(expectedDate, footballtime);
You could call ToString() with whatever format you want your time to be in for comparison.
var expected = "28/05/2017 20:00:00";
//Use HH for 00-23, use H for 0-23, use hh for 01-12 and use h for 1-12
Assert.AreEqual(expected, footballtime.ToString("dd/MM/yyyy HH:mm:ss"));
However it seems like you should be comparing both in the proper format (DateTime).
Ask yourself why you are initializing the times via string (football.Time = "20:00:00";), why not use the proper data type for Dates and Times (DateTime)

Change the datetime format from '2014-03-11T14:10:46+11:00' to '20140311141046+11:00'

I am getting the dateTime value in the format 2014-03-11T14:10:46+11:00.
I need to change this into the format 20140311141046+11:00.
The method I am using right now is:
private string changeDateFormat()
{
DateTime dt = Convert.ToDateTime("2014-03-11T14:10:46+11:00");
return dt.ToString("yyyyMMddHHmmss");
}
It seems to be working fine but with one catch.
Instead of showing the output like 20140311141046+11:00,
the output is 20140311084046.
I think I need to pass the timezone too while converting to string. But I am blank on how to do that.
PS: This +11:00 is dynamic can can change in the input. Please suggest a generic solution/approach.
Since you parse it to DateTime you lost the offset part.
I would parse it to DateTimeOffset instead of DateTime and use K format specifier with it's format like;
var str = "2014-03-11T14:10:46+11:00";
var dto = DateTimeOffset.Parse(str);
return dto.ToString("yyyyMMddHHmmssK");
returns
20140311141046+11:00

Converting datetime format without using SAP RFC with C#

I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}

Date read from Database in wrong format?

I'm using DateTime in my C# winforms tool, and I'm storing dates into an SQL database using this line:
iDisc.acquirementDate.ToString("yyyy-MM-dd")
The SQL database field is of DATE type, and when this date is stored, its stored correctly, such as this: 2013-03-14
When I want to the value, I use this line:
DateTime acquirementDate = DateTime.ParseExact(iDiscRow[TableNames.Discs.acquirementDate].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
However, a FormatException occurs at the above line, because the string being parsed is not a valid DateTime complaint string.
The value this is being parsed is the this: 3/14/2013 12:00:00 AM
What I don't understand is, why is the value read as 3/14/2013 12:00:00 AM, when in the database its stored as 2013-03-14 ?
I'm using SqlDataReader to retrieve the data from database. Can post that code here, but I don't think its needed as its very basic.
It seems that your iDiscRow[TableNames.Discs.acquirementDate] is DateTime already. In that case you just have to cast it.
DateTime acquirementDate = (DateTime)iDiscRow[TableNames.Discs.acquirementDate];
And reason why you're getting 3/14/2013 12:00:00 AM is that DateTime.ToString() uses current thread culture to trasnform DateTime to string. Since it's WinForm app, I guess this is your Windows system format for DateTime.
The row is retrieved as an object. The ToString() method is formatting it. You need to pass the format you want to use to the ToString() method.
This answer is only relevent if it's possible for the database value to be null. That is frequently my own situation, so I wrote this function in a helper class in a class library.
public DateTime? SetDateTimeValue(DataTable dataTableIn
, int rowNumber, string fieldName)
{
DateTime? returnValue = new DateTime?();
DateTime tempValue = new DateTime();
try
{
string fieldValueAsString = dataTableIn.Rows[rowNumber][fieldName].ToString();
result = DateTime.TryParse(fieldValueAsString, out tempValue);
if (result)
returnValue = tempValue;
}
catch
{
returnValue = null;
}
return returnValue;
}
Here is a sample call
DataTable data = dataAccess.GetEmergencyVisitDataFromClinicalApplicationSupport(VisitID);
if (data.Rows.Count == 1)
{
ValueSetter setterOfValues = new ValueSetter();
skip a bunch of lines.
AdmitDecisionDateTime =
setterOfValues.SetDateTimeValue(data, 0, "admit_decision_datetime");

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

Categories

Resources