Laravel equivalent of sql datetime casting - php

I have a table which consist of ddate and time_start column and I wanted to compare it to today.
In SQL Server, I can directly cast ddate and timestart to format my desired date and compare it to GETDATE().
In my case, how do I compare the separate (ddate and time_start) to today?
EDITED
What I wanted is to concatenate it like '2020-06-01 11:23:00' and then compare it to today

The content of whereRaw() should be similar to what you're doing in plain SQL. If not, feel free to customize it.
DB::table('your_table')
->whereRaw('CONCAT(ddate, " ", time_start) = GETDATE()')

Related

MySQL comparing stored date with current date and execute

I have stored dates (dd/mm/yyyy) in text format in a table in a field called dates. I want to compare those dates with the current date and if the dates are smaller (if the dates have passed) to move the entire row into a new table called archive. Tried something with the DATEDIFF() but I'm new to MySQL and can't figure it out.
I'm going to preface my answer with a short remark: storing "date" values in SQL database in VARCHAR columns is an anti-pattern. MySQL provides native datatype DATE which is designed to handle "date" values. But that's just a remark, doesn't answer your question.
You can use the convenient MySQL STR_TO_DATE function to convert strings into DATE values. For example:
STR_TO_DATE('15/05/2015','%d/%m/%Y')
You could use a column reference in place of the literal, e.g.
STR_TO_DATE(t.mycharcol,'%d/%m/%Y')
and that will return a DATE value you can compare to another DATE value, using the standard inequality operator < for example.
To return the current date from the database, you can use an expression such as
DATE(NOW())
Putting that together, you could write a query like this:
SELECT t.*
FROM t
WHERE STR_TO_DATE(t.mycharcol,'%d/%m/%Y') < DATE(NOW())
If you want to take the result from a SELECT statement and insert those rows into another table, you can use the INSERT ... SELECT form of the INSERT statement.
Reference: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
Beware of the behavior with badly formatted or invalid dates, e.g.
SELECT STR_TO_DATE('35/05/2015','%d/%m/%Y')
, STR_TO_DATE('15-05-2015','%d/%m/%Y')

SQL Query On Date When Type Is VARCHAR

I'm trying to query a database with a between 2 dates... The problem is the column that I am querying contains dates that are currently formatted like this "01/01/2014" (dd/mm/yyyy) with a column type of VARCHAR.
At the moment, I can't convert the column to a date type.
Basically when I query the table because it's not set to date type the between query doesn't return the correct rows...
Has anyone else come across this problem, is there something I can change within the query?
$this->db->where('IssueDate >=', '02/12/2013');
$this->db->where('IssueDate <=', '22/01/2014');
$query = $this->db->get('MYTABLE');
Thanks guys.
The solution is to use str_to_date():
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') >=", "'2013-12-92'");
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') <=", "'2014-01-22'");
$
You may not have any control over the database. But you do have control over your own constants. You should get used to the ISO standard YYYY-MM-DD for such constants -- unambiguous and accepted correctly by most databases.
I might suggest creating a view on the table in the database that transforms the string date columns you have into the following format... YYYYMMDD
That format is sortable and can easily be compared versus other similar formatted dates - you can even do date arithmetic with it.
Keep in mind that a view does not copy the table or add any performance overhead. It is often a good idea to access any table through a view even if initially you do not need to perform any manipulations on the underlying table - it will help if you later find you do need to perform them.
use BETWEEN clause with STR_TO_DATE(). Check below code:-
$wh = STR_TO_DATE(`IssueDate`,'%d/%m/%Y')." between '02/12/2013' and '22/01/2014'";
$this->db->where($wh);
Expect it'll give You perfect result.

Selecting records between two dates using PHP from MySql database

In my project , I am generating and storing the Bill (invoice).
The date of Bill is coming to the textbox from the javascript date picker(small pop-up calender) before saving.
The format of the date is : DD-MON-YYYY (18-JUN-2013).
I am using 'Text' data type for storing dates in MySql table.
I have done selecting of records(Previous Bills) from the table by given single date like. . .
$result = mysql_query("SELECT * FROM outward WHERE date='".$date."' ORDER BY billNo");
Now, what i want to do is:
To select records (Bills) between two dates.....
My exact Question is:
Is it possible to query mysql database with this settings or I have to make some changes to select records between 2 dates efficiently ?
How can i achieve this ?
P.s. - Is it effective to use
1. "SELECT * FROM outward WHERE date BETWEEN '" . $from_date . "' AND '" . $to_date . "' ORDER by id DESC"
Or
2. SELECT * FROM outward WHERE date > "15-JUN-2013" and date < "18-JUN-2013"
You could do it in a pure SQL way, but you are going to have to do a full table scan for each query.
select the_dates,
STR_TO_DATE(the_dates, '%d-%M-%Y') as converted
from testing
where STR_TO_DATE(the_dates, '%d-%M-%Y') between '2013-06-20' and '2013-06-23'
Link to SQLFiddle
You should use strtotime PHP function to convert string date to UNIX timestamp format and change MySQL data type for date field to TIMESTAMP.
Than you can do effective queries with > and <.
If it's a DATE column, you can get all dates between 15 June 2013 and 18 June 2013 (inclusive) using this:
WHERE date BETWEEN '2013-06-15' AND '2013-06-18'
If it's a DATETIME column, do this instead:
WHERE date >= '2013-06-15' AND date < '2013-06-19'
If the date column is indexed, this approach will make sure the indexes are available for optimization. If it isn't indexed, the approach is just as fast as the many other ways you can do this.
Addendum: Just saw the "storing as text" amidst all the other shouted info. Note that this answer applies only if the type is DATE or DATETIME. I'll leave it up because the best answer is to change the column's data type and then use this or one of the other suggested options.
I am using 'Text' data type for storing dates in MySql table.
That's a problem. You should store dates as date or datetime data type in MySQL. If you don't care about the time part, date should be sufficient.
If you change your data type to date, then doing:
select x,y,z from table a where a.datecolumn between #startdate and #enddate
Should work fine.
If you use a text data type, you would have to cast the column to a date column and then apply your date selection range which is going to be slower due to the cast.
Always store data in the data type that matches its kind. If a date then a date column, if it's text then text or varchar, etc. The presentation layer of your app can worry about the format in which this data is presented to the user.
You said you were using a TEXT column to store the dates. That's an extremely bad idea. If you switch to a DATE or a DATETIME, then this becomes trivial.
Since you are storing it as text but you want SQL to parse it as a DATE SQL doesn't understand in the first place.
In your example SQL will use TEXT comparison rules. So 15-April < 15-Mar > 15-DEC
If you are storing dates in an SQL database you should be storing it as a Date and not as TEXT.

Query The Table Using PHP Substr() Function

I have a case to query the table using WHERE clause in which I just want to use a 'piece of string' from the field to compare to my string as a condition for selecting.
In the picture, I just want to use month and year from date field to compare with $indicator = 03/2013.
Any idea how can performing the query, so the result would look like:
Any help will appreciated. Thank you in advanced.
Most likely, you aren't dealing with strings in the table, as it's most likely dates. If you are dealing with strings, it's
SELECT * FROM table WHERE DATE LIKE '%03/2013';
where % is a wildcard like * in the old dos days
For actual date fields, (which you would be better off using), it's a simple between
SELECT * FROM table WHERE DATE BETWEEN '01/03/2013' AND '31/03/2013'
Note that you need to follow proper date formatting for your engine, for something like MySQL you'd be better off using '2013-03-01' and '2013-03-31'
The hardest part will be coming up with the first and last day, but for that, I'd look at strtotime(), which allows you to put in things like 'Last day of the month' and such. You'd have to format it correctly, and play with the strings, but it's rather trivial with what strtotime() can do.
USE LIKE in your mysql query instead of =
Reference : (source)

mysql date string between two date query doesn't work

I am trying to get a report between two date and I don't know What is the best way, I did a query but sometimes it doesn't work and I dont know where the error is.
Thank you again.
I am saving datetime in mysql field type varchar with php date('h:iA d-m-Y').
Example in mysql row date:
09:22AM 26-06-2015
08:00AM 27-06-2015
10:00PM 28-06-2015
When I use this data example $since=01-06-2015 $until=30-06-2015 this works
But if I use this data $since=01-06-2015 $until=01-07-2015 this doesn't work.
$since = $_REQUEST['since'];
$until = $_REQUEST['until'];
mysql_query("select * from paradas where DATE_FORMAT(STR_TO_DATE(SUBSTR(date, 9),'%d-%m-%Y') , '%d-%m-%Y') between '".$since."' and '".$until."' ");
By storing your date and time as a VARCHAR, instead as a DATETIME you also change the comparison between two rows from a datetime comparison (chronological) to a string comparison (lexigrafical).
If you now (as in your example) chose a string representation, where the lexigrafical comparison provides different results than the chronological comparison, you can no longer use contructs like BETWEEN or operators like <= and friends.
Solution: If you want to store date and time information, use the DATETIME column type.
In addition to that let me direct you to this SO question for a discussion of your SQL query.
EDIT
Just to make that clear:
In a lexigraphical order '01-06-2015' < '20-06-2015' < '30-06-2015', which is the same as the chronological order
But in a lexigraphical order '01-06-2015' < '01-07-2015' < '20-06-2015', which is contrary to chronological order.

Categories