Mismatches on DateTime between C# and SQL server - c#

I create DateTime in C# like this
DateTime oDate = Convert.ToDateTime(xate);
that returns 22/09/2020 01:27:00 ب.ظ}
and save it in SQL server after saving I see the time that stored is Weird
like this
and when I try to run a SQL command like this
INSERT INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098','22/09/2020 12:00:00 ق.ظ', '22/09/2020 12:00:00 ق.ظ');
I get this error
Conversion failed when converting date and/or time from character string.
I figure out the time that generates in C# is vice versa the format in the SQL Server.
I don't know how to save DateTime in C# to SQL Server.
My code for saving datatime in SQL Server is:
HomeVisitRow homeVisit = BehzistiDb2.List<HomeVisitRow>().Where(x => x.LifeplusCaseId == lifeplusCaseId && x.FromDateTime <= oDate && x.ToDateTime > oDate).FirstOrDefault();
if (homeVisit == null)
{
homeVisit = new HomeVisitRow
{
Id = Guid.NewGuid(),
LifeplusCaseId = lifeplusCaseId,
FromDateTime = oDate,
ToDateTime = oDate.AddMonths(6)
};
BehzistiDb2.Insert<HomeVisitRow>(homeVisit);

Conversion failed when converting date and/or time from character
string
The problem is that you insert a string ' ' into your SQL Database instead of a DateTime Object like you specified.
We can create a DateTime Object from a string easily if we use DateTime.TryParseExact()
Example:
DateTime fromDate;
string txtStartDate = "22/09/2020 01:27:00";
DateTime.TryParseExact(txtStartDate, "dd/MM/yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out fromDate);
Console.WriteLine(fromDate.ToString());
Now we can also insert that Variable into our SQL Statement as it's value.
INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098', fromDate, toDate);

You format the date according to your requirement just see the below examples.
DateTime oDate = Convert.ToDateTime(xate);
oDate = oDate.ToString("yyyy-MM-dd");

Related

Trying to convert string format (dd-mm-yyyy hh:mm:ss) in (yyyy-mm-dd hh:mm:ss) date format

I am capturing date from oracle in a string variable in this format
string val1 = "30-03-2019 16:42:58" and trying to store it in sql database in (datetime) format eg val2 = "2019-03-03 16:42:58.000"
Storing date from oracle db in string variable
string val2 = row["t_in_o"].ToString();
and inserting in sql like
myCommand.Parameters.AddWithValue("#t_in_s",val2);
Expected
string val2="30-03-2019 16:42:58"
string variable val2 should be stored in
date variable date_V as date_V="2019-03-03 16:42:58.000"
Error message
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
You need to first convert your date string to datetime.
string val2= row["t_in_o"].ToString();
Datetime date = DateTime.Parse(val2);
myCommand.Parameters.Add("#t_in_s", SqlDbType.DateTime).Value = date;
Oracle dates don't really have a format.
If you want to stor a string in the DB, just tell oracle it's a date with to_date
insert into Mytable (thedate)
values
(to_date(:stringval1, 'DD-MM-YY HH24:MI:SS'))
At first note that you trying to store value with milliseconds to you SQL Database but you haven't it in string that you getting from oracle (due to post summary), so it will be always .000.
But the this that you are asking can be done using following code:
string val2 = DateTime.ParseExact(row["t_in_o"].ToString(), "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd HH:mm:ss.fff");
Note that i didn't knew in what type you storing value in row["t_in_o"] so i counted it as string, if you converted this value to DateTime already just remove useless Convert.ToDataTime and use row["t_in_o"].ToString("yyyy-MM-dd HH:mm:ss.fff");

How to convert this date 2017-07-09T17:50:21.000-0500 | C#

when i run the below code,
string dt = "2017-07-09T17:50:21.000-0500";
DateTime date = Convert.ToDateTime(dt);
it gives me output as
7/10/2017 4:20:21 AM
where as i want my output to be
2017-07-09 17:50
update
the code #alexander-petrov gave worked
string dt = "2017-07-09T17:50:21.000-0500";
string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");
gives output
2017-07-09 17:50
but on inserting the same to database it is adding +5 hrs to the time and inserting as
2017-07-09 22:50
This is a Round-Trip format of a DateTime specified with a DateTimeKind.Local kind.
You need to decide if your program needs to be aware of time zones or not.
You could try parsing it while supplying the System.Globalization.DateTimeStyles.RoundtripKind or System.Globalization.DateTimeStyles.AdjustToUniversal parameter to the Parse method.
If you want take offset into account then use DateTimeOffset type.
string dt = "2017-07-09T17:50:21.000-0500";
DateTimeOffset date = DateTimeOffset.Parse(dt);
// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);
// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);
I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:
DECLARE #stringDate VARCHAR(30);
SELECT #stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE #xmlDate XML;
SELECT #xmlDate = CAST('' AS XML);
SELECT #xmlDate.value('xs:dateTime(sql:variable("#stringDate"))', 'datetime');
Results:
2017-07-09 22:50:21.000
Try:
string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

Date in c#, mysql

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

How to convert dd/mm to Mysql Datetime format in c#

I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00

convert back datetime format toLongdatestring to (M/DD/YYYY h/mm/ss)

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.

Categories

Resources