Replace DAY at end of Date - php

I have a column in MySQL stored as: 2014-03-16 (for March 16, 2014). It has been decided that the fields should all be changed to the first day of the month -- whatever months in which they occur. I have records that span from 1998 to present day, several thousand of them. Is there an easier way to change just the DAY (in this case, 16) on all the records besides REPLACE 2014-03-16 with 2014-03-01?
I am using PHP, so if it's easier to change it there let me know.

You can do it using a MySQL query:
UPDATE your_table
SET date_column = DATE_FORMAT(date_column ,'%Y-%m-01')

Related

MySQL grouping by season

Im trying to figure out the most efficient way of calculating statistics using data from MySQL database with dates.
Currently, I use the following syntax
Example:
SELECT sum(Precipitation) from DataTable GROUP BY YEAR(Datetime)
This works perfectly fine, I get the total rainfall for each year. However, now I would like to implement the option to set the beginning of the rain season. In some places, the rain season might begin for example in September. In such case I would need the same calculation, i.e. also grouped by "years", but always since Sep to Aug.
I was thinking about how to do this and the only way I can think of would be somehow calculating the monthly sums and the using PHP try to add them up. But the problem is that that would probably be much slower given there is lots of data and the original script uses just this one line above.
Is there any more efficient way of then getting something like
2014 - xyz inches, 2015 - xyz inches, but where the 2014 would correspond for example to season 2014/2015 etc.
The data in the table is like this: column 1 is always the Datetime and then the actual value, data in 5 minute intervals. I need to maintain the table structure, so I cannot create a different table where the values would be organized differently.
Use this query:
SELECT SUM(Precipitation)
FROM DataTable
GROUP BY YEAR(DATE_SUB(Datetime, INTERVAL 8 MONTH))
This query shifts every date backwards by 8 months, with the result that September 1, 2016 would appear to be the first day of 2016, and August, 2016, would appear to be the last month of 2015.

Mysql search between two date with time

how to search between two date , when date format in database like :
2015-10-10 02:23:41 am
i just want to search between two date with format :
2015-10-10
without
02:23:41 am
any ideas please ?
Your question isn't completely clear. But, I guess you hope to find all the rows in your table where Date occurs on or after midnight on 2015-08-05 and before midnight on 2015-09-11 (the day after the end of the range you gave in your question.
Those two search criteria will find all the rows with Date values in the range you specified. (I'm ignoring the 02 at the end of 2015-09-10 02 in your question because I can't guess what it means, if anything.)
Try this query:
SELECT *
FROM table
WHERE `Date` >= '2015-08-05'
AND `Date` < '2015-09-10' + INTERVAL 1 DAY
This has the benefit that it can exploit an index on the Date column if you have one, so it can be fast.
You could write
SELECT *
FROM table /* slow! */
WHERE DATE(`Date`) BETWEEN '2015-08-05' AND '2015-09-10'
That's slightly easier to read, but the WHERE condition isn't sargable, so the query will be slower.
Notice that the beginning of the range uses >= -- on or after midnight, and the end of the range uses < -- before midnight.
Pro tip: Avoid the use of reserved words like DATE for column names. If you make mistakes writing your queries, their presence can really confuse MySQL, not to mention you, and slow you down.
May I suggest:
select * from table where cast(date as date) between '2015-08-05' and '2015-09-10'
When your where clause is based on a timestamp, but you're using date as the parameters for your between, it excludes anything that happens on the second date unless it happened precisely at midnight.
When using the end date for the range, include the time of the end of the day:
SELECT *
FROM YourTable
WHERE date BETWEEN '2015-08-05' AND '2015-09-10 23:59:59'

how to separate Day and Night Record using Mysql Statement

In my SQL database I store date with time stamp for example like this(2015-09-21 18:02:14) I have requirement to get last time(18:02:14) is Day or Night using SQL statement
If you have another idea please share with me. I would like to use it if it fits my requirements.
In my table if have 20 record same date then get only day record how to create query like that
If the day defines from 6am to 6pm, Then
SELECT column
FROM `tablename`
WHERE HOUR( column )
BETWEEN 6
AND 18;
First you should define what is a day and night. Then you can use DATE_FORMAT function to convert datetime field to HH:MI string.
For example you can select records from 18:00 to 8:00 (Night)
select * from t
WHERE DATE_FORMAT(dt, '%H:%i')>='18:00'
or DATE_FORMAT(dt, '%H:%i')<'09:00'
SQLFiddle demo
You should have another table (or other data source) that supplies the sunset and sunrise times, then compare you own datetime, to that source. You can compare either before adding to your table (and make another column named isDay) or when SELECTing from the table.
Note:
Sunset/Sunrise times depend on your geo-location.
There are API's that can provide that info
There are algorithms that can assist in calculating that info
Examples:
http://sunrise-sunset.org/api
http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2015-12-13
I need a sunrise/sunset webservice api
-- from sql server 2008 until now
SELECT
CASE WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 'DAY'
ELSE 'NIGHT'
END
-- from sql server 2012 until now, if you don't like CASE
SELECT IIF(DATEPART(HOUR, GETDATE()) < 18, 'DAY', 'NIGHT')
18 = 6PM
you can replace GETDATE() with your DATETIME column
SELECT
CASE WHEN DATEPART(HOUR, 'yourDateTimeColumn') < 18 THEN 'DAY'
ELSE 'NIGHT'
END AS PeriodOfDay
FROM 'yourTable'

Select all records between two dates created between time of day - MySQL

I'm using Laravel 3 - PHP and MySQl.
I need to select all records created between two dates (created_at DATETIME) and between two times (3pm and 6pm).
$query->where_between('created_at', $this->s['start'], $this->s['end']);
How can I add a time range to that for between 3pm and 6pm between those days?
Edit
$this->s['start'] = '2014-2-14';
$this->s['end'] = '2014-2-16';
Timerange: 06:00:00 and 09:00:00 UTC
Dates are stored in Datetime like 2014-2-15 06:43:56
Example data
Records:
Between 2014-2-14 and 2014-2-17 AND between 07:00:00 and 14:00:00.
2014-2-15 06:43:56
2014-2-16 08:43:56*
2014-2-17 15:43:56
2014-2-17 10:43:56*
2014-2-18 12:43:56
2014-2-19 14:43:56
2014-2-20 16:43:56
* selected record
Along the lines of:
$query->raw_where('EXTRACT(HOUR_SECOND from `created_at`) between 070000 and 140000');
Simpler way to do this?
Why are you not doing this using sql? Filtering is part and parcel of SQLs raison d'etre. Indeed, the between clause exists for precisely this reason:
SELECT pkid from tbl where datetime_field between 7:00:00 and 14:00:00
I'd recommend keeping the filtering as close to the database as is reasonably possible, given the constraints of the database itself.
I think that you just have to add an other where_between constraint to your request :
$query->where_between('created_at', $this->s['start'], $this->s['end'])
->where_between('created_at', '6:00:00', '9:00:00');
Never tried but it should do the job !
Thanks to hd1 for SQL tip.

Store month and year in mysql database

I have following date:
$params['ExpirationMonth'];
$params['ExpirationYear'];
I need some suggestion regarding how can I store only month and year in mysql database. After some research I have found 3 ways to do it.
1) I can use 1st as the days and can store along with month and year.
2) Instead of using date I can use varchar datatype and can only store month and year in it.
3) I can store the two as two separate columns as integers. i.e. for month and year.
Which is the better way?. Need some suggestion. Thanks.
You can use a date column, keeping in mind that:
You could set the day portion to 1
The card is good for the entire month of the specified expiry date. 0512 means valid through 31 May 2012.
Advantages:
Sorting is straight forward (compared to storing as varchar)
Date operations are straight forward (compared to storing as varchar/two integer columns)
Data stays in one column (compared to storing as two integer columns)
Sample queries:
-- expires in 2012
WHERE expires >= '2012-01-01' AND expires < '2012-01-01' + INTERVAL 1 YEAR
-- expires in Dec 2012
WHERE expires >= '2012-12-01' AND expires < '2012-12-01' + INTERVAL 1 MONTH
1) I can use 1st as the days and can store along with month and year.
This option is better as if there is any calculation or sorting need
to be done, it will be useful and handy.
2) Instead of using date I can use varchar datatype and can only store month and year in it.
3) I can store the two as two separate columns as integers. i.e. for month and year.
For above two option are fine as it will take less space as compare to
date or timestamp. But you can do calucation or orderby with this. For
calculation you need to convert it date by "str_to_date" function
I hope this will help you in some way.
stored as UNIX. suddenly need to add something in the future, and no problem to get anything out of date
Expiration Month/Year from credit cards means that this card is valid until the end of this Month/Year.
Best way to store as a comparable date you should get the last day of this month
STR_TO_DATE( CONCAT( '01,', #Month, ',', #Year, '%d,%m,%Y )
+ INTERVAL 1 MONTH
- INTERVAL 1 DAY
You can always store it like YYYYDD as an integer:
So for May 2021 you can store this integer: 202105

Categories