How to get Datetimepicker with seconds in asp.net? - c#

i have a task that i have to filter the records based on DateFrom and DateTo.
in mysql the date fromat is in '2014-07-18 20:03:08' like this.
In front end i used DatetimePicker to textbox..datetimepicker format results gives
'2014/07/09 14:00'.
so not possible for compare db dateformat and datetime formate.
i want datetime picker with seconds..plz help me

A DateTimePicker stores a DateTime in the Value property. You can add desired seconds to it:
DateFrom.Value = DateFrom.Value.AddSeconds(seconds);
datetimepicker format results gives '2014/07/09 14:00'.
Don't use strings as parameters for datetime-columns in MySql. Instead use sql-parameters and pass the DateTime directly:
// add seconds if you want, but i don't see any reason for it
// maybe you want to include the To-date, then you can add a day - one second
DateTo.Value = DateTo.Value.AddDays(1).AddSeconds(-1);
using (MySqlConnection conn = new MySqlConnection("connStr"))
{
try
{
conn.Open();
string sql = #"SELECT t.From, t.To, OtherColumns...
FROM TableName t
WHERE FROM >= #From AND To <= #To";
using(MySqlCommand cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#From", DateFrom.Value);
cmd.Parameters.AddWithValue("#To", DateTo.Value);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// ...
}
}
}
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

DateTime pickers aren't always made for this accuracy.
I suggest using a customized DateTime picker with textboxes to allow your users to input complete time in seconds.

Related

C# sqlite reader isnt returning anything past the first hyphen in a date time

I am inserting a DateTime attribute into a sqlite database and its getting stored successfully as 2018-04-09T00:00:00.0000000-03:00 for the appropriate time. When I attempt to retrieve it from the database it only returns 2018. Why won't it return the full value?
my insert is:
using (SQLiteConnection conn = new SQLiteConnection(Utility.CONN_STR))
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand("INSERT into Waybill (createdOn) VALUES(#createdOn)", conn);
cmd.Parameters.AddWithValue("#createdOn", waybillP.CreatedOn);
cmd.ExecuteNonQuery();
}
createdOn is a DateTime.
My select is:
using (SQLiteConnection conn = new SQLiteConnection(Utility.CONN_STR))
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Waybill where WaybillId = (select max(waybillId) from Waybill);", conn);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int waybillId = Convert.ToInt16(reader["waybillId"].ToString());
var temp = reader["createdOn"].ToString();
DateTime createdOn = DateTime.Parse(temp);
waybill.WaybillId = waybillId;
waybill.CreatedOn = createdOn;
}
Temp is only returning 2018 instead of 2018-04-09T00:00:00.0000000-03:00.
I have tried setting the DB column to text, real, and integer with the same results.
I have also tried using SQLites datetime formatting like so:
SQLiteCommand cmd = new SQLiteCommand("INSERT into Waybill (createdOn) VALUES(datetime('now'))", conn);
every attempt just returns 2018 no matter what the actual entry in the DB looks like.
This causes the DateTime.Parse to crash as 2018 isn't a recognized date time.
Any help would be appreciated.
Chetan's solution worked for me since I am only returning one result and I know the contents of the reader to be able to select the index.
var createdOn = reader.GetDateTime(1);
So for anyone reaching here after so much searching:
The Problem:
your datetime record in your sqlite database might look like this: 2019-11-24T08:43:52.1083280Z and when you try to parse your date field into either a string or DateTime or even a dynamic field you only get until the first hyphen in this case 2019.
I'm using the System.Data.Sqlite and Dapper packages.
since I did not have enought time to investigate this thoroughly, this code helped me:
The Solution:
first alter your query to return something other than that date format:
select strftime('%Y%m%dT%H%M%S', created) as created from contacts
then you can either parse that format in your code or implement a custom TypeHandler for Dapper.
Parsing the custom format:
DateTime.SpecifyKind(DateTime.ParseExact(value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture), DateTimeKind.Utc)
Custom Dapper TypeHandler:
public class DateTimeHandler : SqlMapper.TypeHandler<DateTime>
{
public override void SetValue(IDbDataParameter parameter, DateTime value)
{
parameter.Value = value.ToString("YYYYMMDDTHHmmss");
}
public override DateTime Parse(object value)
{
return DateTime.SpecifyKind(DateTime.ParseExact((string)value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture), DateTimeKind.Utc);
}
}
Which you have to register it in the begining of your application for example in Global.asax:
protected void Application_Start()
{
SqlMapper.AddTypeHandler(new DateTimeHandler());
}

Comparing C# datetime value to SQL Server Compact 4 datetime

I'm building an application that stores a group of datetimes to keep track of when I print a particular report. The report is built up of information from a second table that also has datetimes. I'm trying to get the report to populate a datagridview with records that are only after the last datetime in the first table.
The first table is called 'deliverylog', this table stores the past print dates. The second table is called 'joblog', and it stores the records of previous job entries.
When I run the program, it works just fine and populates the gridview with all records after the last date, but it's not refined... it only populates with dates after the date and not the time. I need the query to populate the gridview to the second....
DateTime lastDeliveryDate;
private void getLastDelivery() // Sets global variable lastDeliveryDate to the last timestamp entered in the deliverylog table
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT TOP 1 * FROM deliverylog ORDER BY Id DESC", logConn);
drLogSet = command.ExecuteReader();
while (drLogSet.Read())
{
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
private void populateGridView()
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT * FROM joblog WHERE TimeStamp > #date", logConn);
command.Parameters.AddWithValue("#date", lastDeliveryDate);
dtLogSet = new DataTable();
bsLogSet = new BindingSource();
daLogSet = new SqlCeDataAdapter(command);
cbLogSet = new SqlCeCommandBuilder(daLogSet);
daLogSet.Fill(dtLogSet);
bsLogSet.DataSource = dtLogSet;
dataGridView1.DataSource = bsLogSet;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
Anyone know how to get the this working right? I'm storing the timestamps for both tables as datetime data types and in the following format: "MM/dd/yyyy hh:mm:ss tt"
I believe that using the AddWithValue method is internally converting the value and probably loosing the desired time precision. Instead, use the Add(String, SqlDbType) method overload of the Parameters collection:
var dateParameter = command.Parameters.Add("#date", SqlDbType.DateTime);
dateParameter.Value = this.lastDeliveryDate;
Make sure you have the correct value before setting the parameter value by inspecting the variable using the debugger.
And you could try using the DATEDIFF SQL function instead of the > operator to ensure proper precision:
SELECT * FROM joblog WHERE DATEDIFF(second, #date, TimeStamp) > 0
The problems is probably this line:
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
Assuming your TimeStamp field is a datetime type, you should use:
lastDeliveryDate = (DateTime) drLogSet["TimeStamp"];
Please confirm the data type of your TimeStamp field.
You should format the date to yyyyMMdd hh:mm:ss.
lastDeliveryDate.toString("yyyyMMdd hh:mm:ss").
In this postare more details.
How to compare sqlite TIMESTAMP values

Compare system date with a date field in SQL

I am trying to compare a date record in SQL Server with the system date. In my example the user first register with his name and date of birth which are then stored in the database. The user than logs into the web application using his name only. After logging in, his name is shown on the side where it says "Welcome "player name" using Sessions.
What I am trying to show in addition to his name is a message saying "happy birthday" if his date of birth matches the system date. I have tried working with System.DateTime.Now, but what I think is that it is also comparing the year, and what I really want is the day and the month only. I would really appreciate any suggestion or help.
CODE In Login page:
protected void Button1_Click(object sender, EventArgs e)
{
String name = TextBox1.Text;
String date = System.DateTime.Today.ToShortDateString();
SqlConnection myconn2 = new
SqlConnection(ConfigurationManager.ConnectionStrings["User"].ToString());
SqlCommand cmd2 = new SqlCommand();
SqlDataReader reader;
myconn2.Open();
cmd2 = new SqlCommand("Select D_O_B from User WHERE Username = #username",
myconn2);
cmd2.Parameters.Add("#username", SqlDbType.NVarChar).Value = name;
cmd2.Connection = myconn2
cmd2.ExecuteNonQuery();
reader = cmd2.ExecuteReader();
while (reader.Read().ToString() == date)
{
Session["Birthday"] = "Happy Birthday";
}
}
Note: I using the same reader in the code above this one, but the reader here is with a different connection. Also, reader.Read() is different than reader.HasRows?
Code in Web app Page:
string date = (string)(Session["Birthday"]); // Retrieving the session
Label6.Text = date;
You can replace the code fragment to compare date above with this one
object dobVal = null;
while ((dobVal= reader.Read()) != null)
{
var storedDob = Convert.ToDateTime(dobVal.ToString());
if(storedDob.Month == DateTime.Now.Month &&
storedDob.Day == DateTime.Now.Day)
{
Session["Birthday"] = "Happy Birthday";
}
}
Use ExecuteScalar instead of ExecuteNonQuery() and ExecuteReader(). If D_O_B column in your database is datetime, you can just cast result to DateTime. If D_O_B column is varchar (or something similar), you have to use DateTime.Parse() to convert string to DateTime. Then just compare Day and Month parts of DateTime instances:
DateTime DOB = (DateTime)cmd2.ExecuteScalar();
DateTime Today = DateTime.Now;
if (Today.Month == DOB.Month && Today.Day == DOB.Day)
{
//Happy Birthday
}
Two ways, within in sql you can do a date compare between months and days using the attached page as a reference
sql date compare (bad way for what you want to do)
2) you can cast the incoming string to date time and do a system.datetime.month and system.datetime.day compare against the casted datetime from sql c# better way
I would chose to do way number 2

Insert date into SQL without taking care of the regional settings

my question looks simple: in my client/server application I want to record a specific date provided by the client.
The problem is that I don't know the regional settings of the client, and I don't know the regional settings of the SQL Server.
How can the client application provide a date in whatever format (last login of a specific user) and store it in a SQL Server table that might be installed with a different regional settings (french, english, italian, german, etc...).
Simple: don't use strings. Use a parameter that is typed as a datetime; can be as simple as:
DateTime when = ...
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "... #when ...";
cmd.Parameters.AddWithValue("when", when);
cmd.ExecuteNotQuery();
}
or with "dapper":
conn.Execute("... #when ...", new { when });
Dates/times are actually just numbers. It is only when you write/parse it as a string that formatting is an issue.
Just store everything in UTC date in sqlserver. And while retrieving the date convert the utc date to the timezone of the user. I hope users timezone is maintained in your database.
You will need a timezone table and a conversion function that will convert the UTC time to the users local time.
to insert a date in SQL use a string in the form 'YYYYMMDD'
what comes from the client-side you sould know what is it
You should use Parameters, but you also can format date to ISO format by date.ToString("s")
Use datetime format, and store dates as UTC time.
You'll probably also be interested in datetimeoffset.
Validation part
DateTime dt;
string YourDate = "Your Date";
if (DateTime.TryParse(YourDate, out dt))
{
//Your Code
}
Stored Procedure Record Insertion/Retrieval
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Date Parameter value";
DateTime dt;
if (DateTime.TryParse(expression, out dt))
{
//Your Code
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
While storing the data in Sql Server Keep the data format consistent and synchronized with the data format while retrieving....

DateTime problem in sql compact

I'm using Sql Compact3.5 as my DB with C# .NET In different systems i'm getting the datetime format differently. In an Windows XP it's retrieving the datetime in the format : MM-dd-yyyy HH:mm:ss and in Media center it's retrieving in the format : MM/dd/yyyy hh:m:ss. Is there any way to make the datetime format free from culture or can i set the datetime format in sql compact so let it be any PC it'll use that format only???
Example :
//TimeOfCall is passed as String using the format DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeCommand SqlceCmd = new SqlCeCommand(
"Insert into myreports(TimeOfCall,Status) values(?,?)", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall));
SqlceCmd.Parameters.Add(new SqlCeParameter("#Status", strStatus));
int RowsaAffected = SqlceCmd.ExecuteNonQuery();
con.Close();
return RowsaAffected;
}
}
While Rertiving the record the query is used in this way :
//FromTime and ToTime are passeed in the same format as while storing
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeDataAdapter SqlceDA = new SqlCeDataAdapter("Select TimeOfCall from myreports where TimeOfCall between '" + strFromTime + "' and '" + strToTime + "' order by TimeOfCall", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceDA.Fill(dtReports);
con.Close();
return dtReports;
}
}
I hope it's clear
Ok, from the code, you're basically doing the right thing the wrong way.
The good news is that you're using parameters - that's exactly right - however you don't need actually don't want to convert the date to a string before setting the parameter value.
Simplest should be to change SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall)); to SqlceCmd.Parameters.AddWithValue("#TimeOfCall", timeOfCall)); where timeOfCall is a DateTime value.
The same applies to the status if that's not natively a string.
If you want to be more explicit about types create the parameter first defining the type and then set it.
For your selection query do the same thing, replace your string concatenation with parameters #fromTime and #toTime and set the parameters directly from the appropriate DateTime values

Categories