Formatting a SQL date into a UK format [duplicate] - php

This question already has answers here:
Convert from MySQL datetime to another format with PHP
(18 answers)
Closed 8 years ago.
I have the following SQL query and I would like to output the ageOnLastSeptember date in a UK (dd/mm/yyyy) format. Can anyone tell me how I can achieve this?
$sql="select ( if(month(now()) < 9, year(now()) - 1, year(now())) - year(dob) - if(month(dob)<9, 0, 1) ) as ageOnLastSeptember,first_name,last_name,dob,school,contact_no,family_id,contact_id from members_family where contact_id = '$contact_id' ";
I tried the following but it did nothing
$sql="select date_format(( if(month(now()) < 9, year(now()) - 1, year(now())) - year(dob) - if(month(dob)<9, 0, 1) ), '%d/%m/%Y') as ageOnLastSeptember,first_name,last_name,dob,school,contact_no,family_id,contact_id from members_family where contact_id = '$contact_id' ";

I think it will much easier and better to format the date using PHP rather than formatting using MySQL. After retrieving the data from MySQL you can format using PHP like
$date = date("d/m/Y", strtotime('2002-05-18'));
The output will be : 18/05/2002
So your PHP code will be :
<td>". date("d/m/Y", strtotime($rows['dob'])) ."</td>
More info on PHP date and its format can be found here: http://php.net/manual/en/function.date.php
Hope this helps you :)

You do not need to do formatting at the database level. If you have dates stored as dates (the correct way), just get the records and send it to the client. Formatting should be done at the control which you are using to display these dates.

Not sure how an age can be formatted as a DD/MM/YYYY date. Doesn't seem logical
To get the age in days you could use something like the following
SELECT FLOOR(NOW(), DATE_ADD(dob, INTERVAL (ABS(DATEDIFF(CONCAT(YEAR(DATE_ADD(NOW(), INTERVAL -8 MONTH)),':09:01'), NOW())) * -1) DAY)) AS Age
FROM members_family
WHERE contact_id = '$contact_id'
That could be customised to give an age in years (gets a bit trickier to be 100% accurate with leap years, especially if you want to cope with every 100th year not being a leap year but every 400th year being a leap year)

Related

SQL Select: Multiple values [duplicate]

This question already has answers here:
Datetime equal or greater than today in MySQL
(10 answers)
MySQL Where DateTime is greater than today
(3 answers)
Selecting entries by date - >= NOW(), MySQL
(6 answers)
Select record(s) from mysql table where date is greater than or equal to today
(3 answers)
MySQL query select all were date is equal to today on datetime
(2 answers)
Closed 3 years ago.
Would somebody mind helping me with this?
I'm trying to select all bookings from my table with a start date of today or in the future. The issue i'm having is that I already have a limit (pagination) and sort.
$today = date("Y-m-d");
$sql = "
SELECT *
FROM `bookings`
WHERE startdate >= $today
ORDER BY `startdate` ASC
LIMIT $offset, $no_of_records_per_page";
Edit: The code above displays all bookings regardless of date, rather than just present/future bookings.
Look at the generated SQL statement -- the current date in the SQL query should be something like '2020-01-02' (including the single quotes). Without the quotes, you'd get weird behavior like the database doing the subtraction and comparing the date against 2020-01-02 = 2017!.
WHERE startdate >= $today
Your immediate problem is that you are not surrounding the date variable with single quotes, so you end up with something like where start_date >= 2020-01-13. MySQL sees an arithmetic operation (2020 minus 1 minus 13 = 2006) and happily executes it. Now it needs to compare column startdate (which is of date datatype or the like) to an integer: for this, it implicitely casts startdate to unsigned: this generates a number like 20200113, which is much bigger than 2006. This is not what you intend.
This woud not happen if you were using parameterized queries.
But bottom line, why bother computing the current date from PHP when MySQL has a built-in for that? Just do: WHERE startdate >= CURRENT_DATE and you are all set.

how to find the next closest date in with my given date mysql and php [duplicate]

This question already has answers here:
Get closest date from MySQL table
(3 answers)
Closed 7 years ago.
Hi i have some examples dates given below.How to find the next closest date in php or in mysql ?
I have some date like 12-04-2015 so now i need to get the closest date after the given date.So in my case my closest date is 15-04-2015.How can i find using PHP and mysql ?? Any one help me
PHP
$date = date("Y-m-d");// current date
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
Mysql
SELECT Birthdate FROM hedging ORDER BY ABS(DATEDIFF(Birthdate , `2015-04-12`)) LIMIT 1
How can i execute the above query in mysql ?
BirthDate
25-03-2015
10-04-2015
10-04-2015
11-04-2015
15-04-2015
30-04-2015
You've not given us much information about what you've tried.
In PHP, store the dates in an array, you can then simply sort it and choose the next value.
In SQL so long as they are stored as dates, then WHERE date > $date ORDER BY date DESC LIMIT 1 will give you the next date.

SQL,PHP: Converting Date Format [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 7 years ago.
I'm having a bit of a problem where both the SQL function and the php function does not convert dates properly when they're in the format of "DD-MM-YYYY". I am using a mysql database and I want to convert the date to "YYYY-MM-DD" before it is entered into the database.
The SQL function:
INSERT INTO lease
VALUES(3, 4, STR_TO_DATE('22-02-2015', '%Y-%m-%d'), STR_TO_DATE('27-02-2015', '%Y-%m-%d'))
Returns as "2022-02-20" and "2027-02-20"
Also, the php function puts the month and day in the wrong place so I have to do "Y-d-m" instead, like so:
$startdate = date("Y-d-m", strtotime('27-02-2015'));
$enddate = date("Y-d-m", strtotime('23-02-2015'));
Although that stores it correctly. Any date where the day is > 12 will reset the date to"1970-01-01" because it thinks the day is the month.
Can anyone help with this?
The format argument for STR_TO_DATE() is the format used for the string argument
So use
STR_TO_DATE('22-02-2015', '%d-%m-%Y'),

How to get exact date from 30 days from specific date? [duplicate]

This question already has answers here:
Add 2 hours to current time in MySQL?
(5 answers)
Add number of days to a date
(20 answers)
Closed 9 years ago.
I have mysql date like this 2013-10-16 17:44:13 and I need to get +30 days from there. I can't use eg. 10th ( month ) and change it to 11th ( month ) as this may be 31 day or 29 depending on the month
I can only think of converting 2013-10-16 17:44:13 to timestamp than + 30*24*60*30, and than this new timestamp back to mysql format
Is there a better way?
You can use strtotime for this:
$date = date('Y-m-d H:i:s', strtotime($date . ' +30 days'));
or do it directly in MySQL using DATE_ADD:
SELECT DATE_ADD(`date`, INTERVAL 30 DAY) as `date` FROM `table`
If you run a newer version of MySQL, you don't need to use DATE_ADD:
SELECT (`date` + INTERVAL 30 DAY) as `date` FROM `table`
Please note that while strtotime is smart enough, MySQL requires you to use DAY. Not DAYS.
Edit: I am unable to find any proof of DATE_ADD being needed in older versions, but I swear that I've heard it somewhere. Take it with a grain of salt and use whatever method you prefer.
since you mentioned mysql you an do it with mysql functions
select NOW() + interval 30 day as NEW_DATE
NOW, could be replaced with a date in your db
select date_field + interval 30 day as NEW_DATE from YOUR_DB

MySQL Date comparison advice

I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks
// If num of months provided is a year, make calculation based on exact year
if ($age_in_months % 12 == 0)
{
// Using 365 days here (60 * 60 * 24 * 365 = 3153600)
$clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
}
else
{
// Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
$clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
}
change that column to type date or datetime
don't use UK date format, use ISO-8601 format
and index on that column
I'd just use the MySQL date logic. You can be sneaky and use the fact that the DOB column is stored as text this lie this:
SELECT whatever FROM users WHERE dob LIKE DATE_FORMAT(CURDATE(), '%d/%m/%%');
This will take the current date, format it like a UK date (the %% turns into a single %). So for today (as I post), that would be '20/12/%'. It uses that for a LIKE on dob, giving you everyone with a birthday of '20/12/(something)'.
It's a little weird, but it actually takes advantage of having the DOB stored in a text format. I'm assuming an index on DOB, although you could get away without it if you don't have too many people.
For the second query, it looks like you're trying to do a 'People who were born 6 months ago' type thing. Is that right? You could so something like this:
SELECT whatever FROM users WHERE DATE_ADD(CURDATE(), INTERVAL -6 MONTH) = STR_TO_DATE(dob, '%d/%m/%Y');
It's not a pretty, and if you want people who were born 6, 18, 30... months ago it won't work. In that case, I'd actually go with something like what you have. It's not ideal, but it would more-or-less work and the results may be close enough for you.
datediff(now(),dob) will give you the difference in days between two dates.
If you want to see whether somebody is at least 18, try if (date_sub(now(),18 years) > dob)
Everybody born in February? if (month(dob) = 2)
See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Edit: and since you're stuck with (for unfathomable reasons) a database showing a date that's not in date format, replace dob with your STR_TO_DATE(dob... section.

Categories