how to compare the time and date using mysql and c# - c#

I have a table logout with columns
logout_id
logout_datetime values format like this(2011-09-08 11:09:09)
and i want to compare the logout_datetime with today date and time also....
for that i have done like this....
string dtStartString = DateTime.Today.ToString("yyyy-MM-dd");
string timeonly = DateTime.Now.ToShortTimeString();
string sql = #"select logout_id";
sql+= string.Format("where logout_datetime = '{0}'",dtStartString );
but it will compares only date in logoutdatetime ,its wrong i want to compare the time also
how can i do this..
would any one pls help on this...

Of course your code is only comparing the date because you are passing only dtStartString which does not have a time part.
try to pass this:
string dtStartString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

Use Parameters.
string sql = "select logout_id from TableName
where logout_datetime=#logout_datetime";
...
cmd.Parameters.Add("#logout_datetime",MySql.Data.MySqlClient.MySqlDbType.Datetime)
.Value=DateTime.Now; // you may assign any value of DateTime type.

You could use the date-format, or extract function.
You should read more about date time functions

Related

Comparing two datetimes to check for a clash but seems to be confusing MM/DD with DD/MM C# ASP.NET

I am trying to check my database for a clash, I am reading up using a reader and calling the value down. My value is 10/12/2018 15:00:00 So I have stored this as #moduleStartTime
My next query checks the database using the above datetime and if it is between any other dates entered.
The issue I am encountering is that there are no clashes, so this shouldn't flag up that there are. I have found that the clash it is returning has a datetime of 12/10/2018 15:00:00
It appears as though somewhere in the search, it is reversing DD/MM
Here is my code
//Reading to get all modules student is enrolled on
string checkclash = "SELECT * FROM cModuleTimes INNER JOIN cStudentModule ON cModuleTimes.ModuleID = cStudentModule.ModuleID WHERE cStudentModule.StudentID=#studentid AND #date BETWEEN[StartTime] AND[EndTime] AND ModTimeID <> #modtimeid";
SqlCommand myCommandclash = new SqlCommand(checkclash, myConnectionclash);
myCommandclash.Parameters.AddWithValue("#date", moduleStartTime);
myCommandclash.Parameters.AddWithValue("#courseid", courseid);
myCommandclash.Parameters.AddWithValue("#studentid", user);
myCommandclash.Parameters.AddWithValue("#modtimeid", moduletocompareid);
//create a sqldatareader object that asks for dats from a table
SqlDataReader rdrreadclash = myCommandclash.ExecuteReader();
if (rdrreadclash.HasRows)
{
while (rdrreadclash.Read())
{
string getname = rdrreadclash["ModTimeID"].ToString();
string gettime = rdrreadclash["StartTime"].ToString();
Warning.Text = "There appears to be a clash with this event..<br><br> <br> <b>Would you like to continue?</b> <br><br>";
}
ViewClash.Visible = true;
YesContinue.Visible = true;
FinishMod.Visible = false;
}
myConnectionclash.Close();
I have tried a couple of conversions but am receiving an issue with string not recognised as a DateTime.
If anyone has any answers on how I would prevent this clash from appearing, I would be very grateful.
Thank you.
moduleDateTime is currently a string, you need to parse it in to a DateTime object where the parsing operation has the proper MM/DD order you want.
DateTime dateAsDateTime = DateTime.ParseExact(moduleStartTime, "dd/MM/yyyy HH:mm:ss", null);
myCommandclash.Parameters.AddWithValue("#date", dateAsDateTime);
You then must format the returned date time back to a string in the format you want.
string gettime = ((DateTime)rdrreadclash["StartTime"]).ToString("dd/MM/yyyy HH:mm:ss ");

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

Change from datetime to date in the session variable using c#

txtdob.Text = Session["DOB"].ToString();
It is displaying both date and time,I need only date to be printed,Is there any type of code that makes to display only date within the code i have mention above.?
If i execute the above code it gives the date format as
9/9/2013 12:00:00 AM
But i just need 9/9/2013
In the database DOB has a datatype of DateTime.
I tried with every line of code you have suggested but its giving error as Specified cast is not valid
session["DOB"] is stored as
Session["DOB"] = ds.Tables["login_det"].Rows[0].ItemArray[5].ToString();
Do i need to change this?
If Session["DOB"] is a DateTime instance you could specify the format:
txtdob.Text = ((DateTime)Session["DOB"]).ToString("dd/MM/yyyy");
If it is not DateTime, but a string, then you will have to modify the code that is storing this value into the session so that it either stores the DateTime or it formats the string the way you want it to be.
Try this:
txtdob.Text = Convert.ToDateTime(Session["DOB"].ToString()).Date.ToShortDateString();
OR
txtdob.Text = Convert.ToDateTime(Session["DOB"].ToString()).ToString("dd/MM/yyyy");
Try this
txtdob.Text = Convert.ToDateTime(Session["DOB"]).ToString("dd/MM/yyyy");
or you can find more formats here

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