php search date with different format - php

At my current database i use date format yyyy-mm-dd.
If i want to search by DOB then must use format yyyy-mm-dd to match it with default date format.
Is there a way to search DOB from whatever user input wether its dd-mm-yyyy or dd/mm/yyyy or yyyy-mm-dd and give out the result???
$keyword = clean($keyword,1);
$result = $db->query("SELECT name, dob, email FROM user WHERE name LIKE '$keyword%' OR dob LIKE '$keyword%' OR email LIKE '$keyword%'");
if($result){
//echoing the result
}

Not easily. First convert the user input to the correct format before passing it to the SQL query.
For example:
if (preg_match('~([0-9]{2})[-/]([0-9]{2})[-/]([0-9]{4})~', $input, $matches)) {
return $matches[3].'-'.$matches[2].'-'.$matches[1];
} else {
return $input;
}

You could match UNIX Timestamps eg:
$timestamp = strtotime($date)
SELECT * WHERE UNIX_TIMESTAMP(dob) = '$timestamp'
Check http://php.net/manual/en/function.strtotime.php for more info on strtotime()
This will make it easier for checking within a date range.

Yes, you should normalise the result in PHP before passing it to your SQL query.
Your code may look something like this...
$dateForSqlQuery = date('Y-m-d', strtotime($input));
...assuming that strtotime() will correctly handle those variations.
On the other hand, you should really break up the user input into a separate day, month and year input, then generate the string yourself.

You can use strtotime to parse pretty much any (reasonably formatted) date to a timestamp, and from there you can convert to any other format.
For example:
$yyyy_mm_dd = date('Y-m-d', strtotime('02/01/2012'));
It's quite a processor heavy function though, strtotime, so do be sparing!

Related

Multidimensional array with different keys to format data

I have multidimensional dynamic array with following structure
$xData["invoice"]["no"]["data"] = "DY-13123";
$xData["invoice"]["date"]["data"] = "01-08-2018";
$xData["invoice"]["total_due"]["data"] = 56890.23;
$xData["invoice"]["due_date"]["data"] = "01-12-2018";
$xData["from"]["name"]["first"]["data"] = "Company Name, Inc";
$xData["from"]["address1"]["data"] = "12345 Sunny Road";
$xData["from"]["address2"]["data"] = "Sunnyville, CA 12345";
I want to allow users to format the data of array by specifying format. For example $xData["invoice"]["date"]["data"]= "01-08-2018"
for this, user can specify the format as date type and formatting as "YYYY-mm-dd". I am storing this format information in another array.
$xFormat["invoice"]["date"] = array("date","YYYY-mm-dd");
$xFormat["invoice"]["total_due"] = array("currency","$");
Now, I need to get the value of $xData and apply the formatting. I have tried getting all keys and applying the format but no success. Please let me know how
to do this.
Thanks in advance
What you need to do is, first take the string in date field and convert it to time, then format it with the format in $xFormat
$time = strtotime($xData["invoice"]["date"]["data"]); //converting the date in string to seconds since January 1 1970 00:00:00 UTC
if ($time === false) { //if the date couldn't be converted to seconds
echo "date is wrong";
} else {
echo date($xFormat["invoice"]["date"]["date"],$time); //yes, double date fields is correct
}
The function strtotime converts a string representation of a time to seconds, which in turn can be used in date. Since you have set $xFormat["invoice"]["date"] as array("date","YYYY-mm-dd"), I had to use $xFormat["invoice"]["date"]["date"]

Generate a data-time format from 2 separated strings

I need to compare date/time that I get from MySQL with a format like: 2013-05-17 15:07:29
From another database, I have data and time separated and in the notation: 130998 081836
I have concatenated the two strings to get only one and I'm trying to convert it to my desired format using:
$dateTimeNmea = $array[9]." ".$array[1]; // 130998 081836
$dateTime = date("Y-m-d H:i:s", $dateTimeNmea); // 1970-01-02 13:23:18
So "it works" on the format but the values are wrong. It could be 1998-09-13 08:18:36
Where is my fault?
It has format siH dmy. Try date_parse_from_format('siH dmy', $string) to get it in array.
130998 081836 is not a format for a date that the date function can understand.
For starters the date() function expects the second param to be a timestamp (read docs for it here)
Then you would need to parse the string into a useable date format via date_parse_from_format and finally into a timestamp
Something like
$string = '130998 081836';
$date = date_parse_from_format('dmY His', $string);
$dateString = date('Y-m-d H:i:s', strtotime(vsprintf('%s-%s-%s %s:%s:%s', $date)));
var_dump($dateString); // var dump just for output/test
The strtotime(vsprintf('%s-%s-%s %s:%s:%s', $date) formats your parsed date into a timestamp which can then be used in date methods second param to get exactly the format you need.

between operator for timestamps in mysql query

I have a form to pick up dates from calender. That form will pass start date and end date. My database table stores date in time-stamp format. I have to create a query to pick records from database table between start date and end date. How can I make a query? I have tried the code below, but which is not working.
if(isset($_POST['filter']))
{
$sid=$_POST['sid'];
$start= date("dMY",strtotime($_POST['start']));
$end= date("dMY",strtotime($_POST['end']));
$res=$db->fetchAll("SELECT * FROM `logfile` WHERE `site_id`=".$sid." AND (date('dMY',`timestamp`) BETWEEN $start AND $end)");
}
Any thoughts?
Thanks.
You're forcing PHP and MySQL to do a lot of useless date/time string<->native conversions for no reason.
Why not simply have:
$start = strtotime($_POST['start']);
SELECT ... WHERE `timestamp` BETWEEN FROM_UNIXTIME($start) AND ...
if $_POST['start'] and $_POST['end'] are already in timestamp format, just don't change them. In other case just convert the string in timestamp:
$start = strtotime($_POST['start']); // where $_POST['start'] might be 2012/08/07
$end = strtotime($_POST['end']);
$res=$db->fetchAll("SELECT * FROM logfile WHERE site_id=".$sid." AND date BETWEEN $start AND $end");
As #Matei Mihai said you don't need to convert $_POST['start'] and $_POST['end'] to timestamp format and you must enclose date columns in quotes.
Also you need to convert date in MySQL compatible format like '2012-08-01'.
"SELECT *
FROM `logfile`
WHERE `site_id`=".$sid." AND
(date('dMY',`timestamp`) BETWEEN '$start' AND '$end')");

PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?

I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!
Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.
You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.
Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...
Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);
Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.
Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().
This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));
$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;

If I have a PHP string in the format YYYY-DD-MM and a timestamp in MySQL, is there a good way to convert between them?

I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
Converting from timestamp to format:
date('Y-m-d', $timestamp);
Converting from formatted to timestamp:
mktime(0, 0, 0, $month, $day, $year, $is_dst);
See date and mktime for further documentation.
When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. Check the MySQL Doc for TIMESTAMP info.
You can avoid having to use strtotime() or getdate() in PHP by using MySQL's UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(timestamp) FROM sometable
The resulting data will be a standard integer Unix timestamp, so you can do a direct comparison to time().
I wrote this little function to simplify the process:
/**
* Convert MySQL datetime to PHP time
*/
function convert_datetime($datetime) {
//example: 2008-02-07 12:19:32
$values = split(" ", $datetime);
$dates = split("-", $values[0]);
$times = split(":", $values[1]);
$newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);
return $newdate;
}
I hope this helps
strtotime() and getdate() are two functions that can be used to get dates from strings and timestamps. There isn't a standard library function that converts between MySQL and PHP timestamps though.
Use the PHP Date function. You may have to convert the mysql timestamp to a Unix timestamp in your query using the UNIX_TIMESTAMP function in mysql.
A date string of the form:
YYYY-MM-DD
has no time associated with it. A MySQL Timestamp is of the form:
YYYY-MM-DD HH:mm:ss
to compare the two, you'll either have to add a time to the date string, like midnight for example
$datetime = '2008-08-21'.' 00:00:00';
and then use a function to compare the epoc time between them
if (strtotime($datetime) > strtotime($timestamp)) {
echo 'Datetime later';
} else {
echo 'Timestamp equal or greater';
}

Categories