Date read from Database in wrong format? - c#

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

Related

how to compare datetime value from database with textbox datetime value

I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.

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

Convert dd/MM/yyyy to yyyy/MM/dd?

I want to convert a string '30/12/2012' to '2012/12/30'. My application is set to "en-CA" however the database accepts yyyy/MM/dd as default.
How can I do this without depending on the current culture info set
at server?
As all the comments have said, but none of the answers have said so far: don't pass this to the database as a string.
Parse any text you receive as early as possible, then use DateTime to represent it everywhere else, including how you send it to the database, via parameterized SQL1. This goes for values of all kinds: convert it into the "natural" type for the data as soon as possible, and keep it in that natural representation for as long as possible. A date isn't a string, and you should only convert it to a string if you really, really need to - ideally just before displaying it to a user.
The parsing can be done with DateTime.ParseExact or DateTime.TryParseExact depending on whether this is "suspicious" data (e.g. from a user) or data which should really be correct and for which an exception is the most appropriate reaction to unparseable values. I suggest you pass in CultureInfo.InvariantCulture with your custom format string. For example:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
(If you do a lot of date/time work, you may also want to consider using my Noda Time project which allows you to express the value in a richer way - in this case you'd probably use LocalDate.)
1 If you're not already using parameterized SQL, but are instead baking values directly into the SQL, you have bigger problems than date/time conversions.
You can specify CultureInfo in Format and most ToString functions.
I.e. DateTime.ToString(CultureInfo) and DateTime.Parse(string, CultureInfo) will let you pars string in one culture (i.e. current or new CultureInfo("en-CA")) and format with another like new CultureInfo("en-us").
Note: you may consider running all DB access under some other culture (i.e. en-US) by setting Thread.CurrentCulture as sometimes number fomats are also impacted (if numbers are storead as string).
If its going to always be in the same format. Then split it on the / character
string[] tempsplit = datestring.Split('/');
and then put it back together
string joinstring = "/";
string newdate = tempsplit[2] + joinstring + tempsplit[1] + joinstring + tempsplit[0];
simple.
First convert your string to DateTime format using
DateTime dt = Convert.ToDateTime("your string value");
Then save it in string using:
string st=dt.ToString("yyyy/MM/dd");
This will convert your date format to any desired format you want without depending on culture
Without going into the issue what format the database accepts or not, you can do the conversion like this:
Convert the String to Datetime like explained here
Change the format and convert it to string again like this
This seems to work.
var x = new string[] { "2012/06/12", "20/06/2012", "111/111/1111" };
foreach (var ds in x)
{
DateTime d = default(DateTime);
try
{
d = DateTime.Parse(ds, CultureInfo.GetCultureInfo("en-CA"));
}
catch (Exception ex)
{
try
{
d = DateTime.ParseExact(ds, "yyyy/MM/dd", CultureInfo.InvariantCulture);
}
catch
{
}
}
if (d == default(DateTime))
Console.WriteLine("error");
else
Console.WriteLine(d.ToString());
}

Convert DateTime for MySQL using C#

I want to change the DateTime for MySQL in C#.
My MySQL database only accept this format 1976-04-09 22:10:00.
In C# have a string who have a date value:
string str = "12-Apr-1976 22:10";
I want to convert for MySQL then it look like:
1976-04-12 22:10
How I can change them or how other programmer do this by using dd mm hh yy method? Can anyone tell me about them?
Keep in mind that you can hard-code ISO format
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
or use next:
// just to shorten the code
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "1976-04-12T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "1976-04-12 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
and so on
If your string format for the DateTime is fixed you can convert to the System.DateTime using:
string myDate = "12-Apr-1976 22:10";
DateTime dateValue = DateTime.Parse(myDate);
Now, when you need it in your specific format, you can then reverse the process, i.e.:
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm");
edit - updated code. For some strange reason DateTime.ParseExact wasnt playing nice.
I would strongly suggest you use parameterized queries instead of sending values as strings in the first place.
That way you only need to be able to convert your input format to DateTime or DateTimeOffset, and then you don't need to worry about the database format. This is not only simpler, but avoids SQL injection attacks (e.g. for string values) and is more robust in the face of database settings changes.
For the original conversion to a DateTime, I suggest you use DateTime.ParseExact or DateTime.TryParseExact to explicitly specify the expected format.
This works for me:
1.Extract date from oracle data base and pass it to variable
string lDat_otp = "";
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "";
}
else
{
lDat_otp = rw_mat["dat_otp"].ToString();
}
2.Conversion to mysql format
DateTime dateValue = DateTime.Parse(lDat_otp);
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm");
3.Pass formatForMySql variable to procedure or to something else

Categories

Resources