How to add date parameter and time now to Entity Framework? - c#

I have a string date parameter as 04/14/2018, and I want to add parameter with this date and time now to field datetime in Entity Framework. As sample
string value_date = '04/14/2018' ;
add.Order_Date = Convert.ToDateTime(value_date);
db.Products(add);
db.SaveChanges();
It's working, the data in database save as 2018-04-14 00:00:00 (the column Order_Date in database with type smalldatetime). If to get date and time now, easy to do this with DateTime.Now (it'll get value date and time as 2018-04-13 09:15:00). So, I want to get date parameter with time now, as sample 2018-04-14 09:15:00. How can I do that ?

Just get TimeOfDay and add to your date.
add.Order_Date = Convert.ToDateTime(value_date).Date.Add(DateTime.Now.TimeOfDay);

You can simply construct a new DateTime object using the order date and the current time.
var orderDate = Convert.ToDateTime("04/14/2018");
var accurateDate = new DateTime(
orderDate.Year,
orderDate.Month,
orderDate.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second);

Related

convert datetime in string format and pass it to query

i have a query where i am passing value in given below format it is working in oracle pl/sql
Select ASE_ID
from ASE_DTLS a
where TO_CHAR(CRT_ON,'YYYY-MM-DD')
between '2020-09-01' and '2020-09-23'
Above query giving output. but when i am trying to pass it through c# query in given below format it is not returning value.
Select ASE_ID
from ASE_DTLS a
where TO_CHAR(CRT_ON,'YYYY-MM-DD')
between :CRT_ON and :CRT_ON";
reciving value from post method in fieldval[0] in '01-09-2020 00:00:00' & '23-09-2020 00:00:00' format.
command.Parameters.Add(":CRT_ON", fieldval[0].From.ToString("yyyy-MM-dd"));
command.Parameters.Add(":CRT_ON", fieldval[0].To.ToString("yyyy-MM-dd"));
while reading it through ExecuteReader getting 0 record.
From & To are as defined in c#
public DateTime From { get; set; }
public DateTime To { get; set; }
and CRT_ON in oracle as date.
Dates both in .NET and Oracle have no format, they are binary values. The query should use parameters with date-related types, not convert the dates to strings, only to convert them back to dates.
The code has other problems too - the same parameter is added twice, with a different value. The query itself is using that single parameter in the BETWEEN clause, effectively turning it into an equality check.
The query should be :
Select ASE_ID
from ASE_DTLS a
where CRT_ON between :CRT_FROM and :CRT_TO
The parameters' type should be DateTime :
var fld=fieldval[0];
command.Parameters.Add(":CRT_FROM", OracleDbType.Date).Value = fld.From.Date;
command.Parameters.Add(":CRT_TO", OracleDbType.Date).Value = fld.To.Date;
DateTime.Date returns only the date part of a DateTime value.
This will work as-is if CRT_ON is a date. If it's a timestamp, the query would return rows only up to :CRT_TO at 00:00. To return dates on that day, the query would have to change to
Select ASE_ID
from ASE_DTLS a
where CRT_ON >= :CRT_FROM and CRT_ON < :CRT_TO
And :CRT_TO should be incremented by one day:
var toParam=command.Parameters.Add(":CRT_TO", SqlDbType.DateTime);
toParam.Value = fld.To.Date.AddDays(1);
You should use date as date. Do not convert it to char.
Select ASE_ID from ASE_DTLS a where trunc(CRT_ON) between to_date('2020-09-01','YYYY-MM-DD') and to_date('2020-09-23','YYYY-MM-DD')

PostgreSQL: 42883 Operator does not exist: timestamp without time zone = text

I am using Npgsql 3.0.3.0 and PetaPoco latest version.
When I run this command:
var dateCreated = DateTime.Now; // just an example
var sql = new Sql("WHERE date_created = #0", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
var category = db.SingleOrDefault<Category>(sql);
I get the following error:
Npgsql.NpgsqlException 42883: operator does not exist: timestamp
without time zone = text
I understand the error message is saying I'm trying to compare a timestamp (date) with a text, however for me it's perfectly valid to compare them as I am expecting the following SQL statement to be built:
SELECT * FROM category WHERE date_created = '2017-02-03 15:00:00'
I don't really want to typecast my database column to text for performance reasons.
You need to cast value to timestsamp:
var sql = new Sql("WHERE date_created = #0::timestamp", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
You need to explicit typecast text to timestamp.
Try using :
TO_TIMESTAMP(date_string,'YYYY-MM-DD')
As #roman-tkachuk answered, you can tell PostgreSQL to cast your string into a timestamp.
Or better yet, you can simply send a timestamp to PostgreSQL directly, rather than sending a string representation of a timestamp and having it cast. To do that, simply send dateCreated directly, without the ToString().

DateTime is saved incorrectly into my database

I'm struggling as why my DateTime is saved incorrectly into my database.
I pass it the value 20/12/2015 (as a string) alongside the format (dd/MM/yyyy) and parse it into a DateTime but it always saves into my SQL Server database as 06/12/2015
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
projectPlan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null); //ShortDateTime is 20/12/2015, DateFormat is dd/MM/yyyy
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan = projectPlan;
this._dc.SaveChanges();
}
Erm, didn't you mean updating the StartDate property of your entity and then saving it back into the database:
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null);
this._dc.SaveChanges();
}
On this line you are basically killing every context EF knows about:
plan = projectPlan;
So if you looked at the actual SQL query generated against your SQL database you would have noticed that exactly 0 rows were updated.
The textual representation is not stored in the server, neither is it in .NET when you have a DateTime object. It is just a large number counting the number of "ticks" from a set time.
You will need to format the date when you select the date out back in to a string, the inserting side can't control it (unless the inserting side also stores the formatting string or you don't store it as a date and instead store it as a string)

Adding time to SQL date query

var datadb1 = DateTime.ParseExact(dateTimePicker1.Text, "dd/MM/yyyy", null);
var timedb1 = DateTime.ParseExact(dateTimePicker2.Text, "HH:mm:ss", null);
var datadb2 = DateTime.ParseExact(dateTimePicker3.Text, "dd/MM/yyyy", null);
var timedb2 = DateTime.ParseExact(dateTimePicker4.Text, "HH:mm:ss", null);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", datadb1);
commanddb.Parameters.AddWithValue("#to", datadb2);
Need to add time check to this query (I`m getting time info from dateTimePicker2 and dateTimePicker4).
Need to add time check to this query
The problem with your code is that you are passing only the date part to check to the SQL query. In order to make your query check both the date and time parts, you have to:
Declare the SQL parameters of data type datetime(SqlDbType.DateTime).
The value you are passing to the sql parameter should be of data type DateTime and contains both parts the date and time parts.
One way to achieve this is by using the same DateTimePciker to pass both date and time parts, then don't use the datetimepicker Text property and use DateTimePicker.Value property instead, it will give you both date and time parts:
SqlParameter fromParam= new SqlParameter("#from", SqlDbType.DateTime);
fromParam.Value = dateTimePicker1.Value;
SqlParameter toParam= new SqlParameter("#to", SqlDbType.DateTime);
toParam.Value = dateTimePicker2.Value;
commanddb.Parameters.Add(fromParam);
commanddb.Parameters.Add(toParam);
Or, by adding both the date part and time part coming from different datetimepickers to the same DateTime variable before passing it to the sql parameter. Something like this:
var datadb1 = DateTime.Parse(dateTimePicker1.Value.ToShortDateString());
var timedb1 = DateTime.Parse(dateTimePicker2.Value.ToShortTimeString());
DateTime datetimeCombined1 = datadb1 + new TimeSpan(timedb1.Hour,
timedb1.Minute,
timedb1.Second);
Then you have to pass this variable datetimeCombined1 to the SQL parameter, the same with the second datetime range, you have to combine both the parts before passing it.
This is assuming that you are using dateTimePicker1 to read the date part only and the dateTimePicker2 to read the time part only.
If you want to use each dateTimePicker for Date or Time seperatly you can define a DateTime variables and Set its Date value and Time Value like this:
DateTimePicker dateTimePickerFromDate = new DateTimePicker();
DateTimePicker dateTimePickerFromTime = new DateTimePicker();
DateTimePicker dateTimePickerToDate = new DateTimePicker();
DateTimePicker dateTimePickerToTime = new DateTimePicker();
DateTime fromDateTime = new DateTime(dateTimePickerFromDate.Value.Year,
dateTimePickerFromDate.Value.Month, dateTimePickerFromDate.Value.Day,
dateTimePickerFromTime.Value.Hour, dateTimePickerFromTime.Value.Minute,
dateTimePickerFromTime.Value.Second);
DateTime toDateTime = new DateTime(dateTimePickerToDate.Value.Year,
dateTimePickerToDate.Value.Month, dateTimePickerToDate.Value.Day,
dateTimePickerToTime.Value.Hour, dateTimePickerToTime.Value.Minute,
dateTimePickerToTime.Value.Second);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", fromDateTime);
commanddb.Parameters.AddWithValue("#to", toDateTime);

format string in datetime c# to insert in MYSQL datetime column

I have code like this:
AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();
When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored. How could i fix it?
The column type is DateTime.
A quick/easy method to insert date or datetime into MySQL is to use the format 'yyyy-MM-dd', or datetime as 'yyyy-MM-dd H:mm:ss'.
Try this
DateTime theDate = DateTime.Now;
theDate.ToString("yyyy-MM-dd H:mm:ss");
Make your SQL look like this.
insert into mytable (date_time_field) value ('2013-09-09 03:44:00');
Your line:
string time = Convert.ToDateTime("10-10-2014 15:00:00");
Shouldn't compile.
I can only guess that you don't have DateTime as type of your column in SQL Server, you should modify it to keep DateTime and then pass a DateTime type object, not a string.
This means that the underlying data type in the database must be Date. Change that to DateTime and it will store the time as well.
DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");
The insert Statement will look kind of like this:
string InsertQuery = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";

Categories