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
Related
I have a database connected to c# windows forms application. I want to get a current date and time from database, and then to use that date and time to insert some other data into database.
When I execute a query select now() from WAMP's mySqlConsole I get what I expect: 12-04-17 12:06:28, but when I run that same query from c# and store the value to string like this: String datetime = cmdDatetime.ExecuteScalar().ToString(); the month becomes Apr in which format i cant insert into db.
Is there a way for c# to store mysql datetime in the same format as it is in mysql?
You can use the DateTime object if possible, or else you will need to convert the date time received to the format you want:
DateTime dateTime = (DateTime)cmdDatetime.ExecuteScalar();
string dateTimeString = dateTime.ToString(CultureInfo.InvariantCulture);
Using the InvariantCulture, you will always get the results in the same way, namely in the en-US settings.
Additionally, you can force the specific format too:
string dateTimeString = dateTime.ToString("dd-MM-yyyy HH:mm:ss");
You have to specify the format for example:
DateTime datet = (DateTime)cmdDatetime.ExecuteScalar();
String datetime = datet.ExecuteScalar().ToString( "dd-mm-yyy HH:mm:ss");
Try That:
DateTime datetime = (DateTime)cmdDatetime.ExecuteScalar();
String datetimeStr = datetime.ToString("yyyyMMddHHmmss");
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
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);
}
hi i have datetime format in database like this
1/18/2014 4:14:52 PM (M/DD/YYYY h/mm/ss)
i convert it to ToLongDateString
string date = Convert.ToDateTime(myQuizOccurrence.occurred).ToLongDateString();
**result ->** **Sunday, January 12, 2014**
i want to convert back again that result date to become same format as database i wonder how to do it?
edited
so far i already try as #matt says using datetime instead string
DateTime dt2 = (DateTime) myDataGridView.CurrentRow.Cells[3].Value;
i already check it's have same format as datetime in database
but when i try to matching in query with this following code
Global.dbCon.Open();
string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = " +dt2+ "
ORDER BY ID";
Global.reader = Global.riyeder(kalimatsql2);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idku = Convert.ToInt32(Global.reader.GetValue(0));
MessageBox.Show(idku.ToString());
}
}
Global.dbCon.Close();<br>
it's give error result
Syntax error (missing operator) in query expression 'Occurred = 1/12/2014 4:18:59 PM'
what i'm missing?
The vast majority of databases you will interact with should be accepting either a DateTime or a DateTimeOffset type directly. You would not use a string when retrieving data from the database, nor when sending data back to it. Therefore, format is irrelevant.
My guess is you are doing something similar to this:
DateTime dt = Convert.ToDateTime(mydatareader["MyDateTime"].ToString());
Instead you should be doing this:
DateTime dt = (DateTime) mydatareader["MyDateTime"];
When you save it back to the database, you should be using parameratized inputs that will take the DateTime directly. If you're trying to concatenate a string to build an SQL statement, you're doing it wrong.
i have datetime format in database like this
The best practice is to store date and time information with DateTime or DateTimeOffset type.
To convert back your string to DataTime you can use this:
string str = "Sunday, January 12, 2014";
var dateTime = DateTime.ParseExact(str, "D", CultureInfo.CurrentCulture);
Note that you loss the time part when you convert it to long date.
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());
}