I think this is a simple question. We have a MySQL database with a DATE field, the date is stored in US format (2010-06-01).
In my PHP page where I'll display the date, I simply want to convert this date into a UK format (01-06-2010).
Any help and advice appreciated!
Thanks,
Homer.
You didn't specify and your example is ambiguous, but I'll assume you're talking about outputting in day-month-year format. You can use strtotime to parse a string date into a unix timestamp, and then give that timestamp to date along with the format that you'd like to output your date in:
date("d-m-Y", strtotime($date_from_mysql));
The manual page for date lists all the formatting options that you can give. In this case, d represents the day as a zero-padded number, m represents the month as a zero-padded number, and Y represents the year as a four digit number. Any characters that don't have a specific meaning for date come across as-is.
You can do it right from mysql using DATE_FORMAT() function.
example : "SELECT DATE_FORMAT(date_column,'%d-%m-%Y') as my_formated_date;" will do what you need , just make sure to use in fetch method my_formated_date column
You can parse the date with this function:
http://php.net/manual/en/function.strtotime.php
It will return an integer which is number of seconds since 1970 (called a Unix timestamp).
Then use this function to format that number any way you like:
http://ca3.php.net/manual/en/function.date.php
You can also create a Date object in PHP using the DateTime::createFromFormat feature.
<?php
$date = DateTime::createFromFormat('Y-m-d', $sql_date);
echo $date->format('d-m-Y');
?>
Related
Currently I'm working on PHP and MySQL Project. I'm taking DATE INPUT from users in string format. So user can enter any format in text-box. For e.g. dd/mm/yyyy or dd-mm-yyyy or yyyy-mm-dd or mm/dd/yyyy etc. (I know its too bad practice). But my question is:
is it possible to convert these all in single format and store it in
single column?
.
For converting I'm using str_to_date() function, but it accepts only one format to convert. How can I add other formats to convert string to date ?
try this, should work:
$mysqlFormatedDate = date('Y-m-d H:i:s', strtotime($yourTime));
PHP will take $yourTime and resolve it's format, then it will convert it to unix timestamp, and then it will convert to mysql datetime format which is Y-m-d H:i:s then you just need to save it to your DB.
you can do this in your mysql_query using STR_TO_DATE:
STR_TO_DATE($yourTime, '%c/%e/%Y %r')
You can use "RLIKE()" to check fo some patterns but that will fail because you can't differentiate between international and retarded. Imagine someone typing in "12/11/2018". Is it the 11th of December or 12th of November? Also you wrote "e.g.", so if you allow everything, what would you make of "20122007"? 20th December 2007, 20th July 2012?
Use a JS-Library for date inputs or do inputs for day, month and year separately. Otherwise it's pretty hopeless.
After spending over 6 hours trying to do this and trying many different published solutions I am just going to ask the exact question.
I want to have the user enter the date and time in US format in an html form. Format for today is 12/16/2012 02:53 using 24 hour time format.
Lets call it start_date.
Then I want to insert the record including the start_date into an mysql database into a datetime type field.
I am using PHP 5.2. Many of the solutions I saw required 5.3 and none of the workarounds for 5.2 worked.
Can someone please give me an exact example.
Thank you.
Use regex or string processing to extract fields from your current format.
Create date in MySQL format.
Insert in the database.
See here : date_create_from_format equivalent for PHP 5.2 (or lower)
Actually the format of your date in not valid to be inserted in mysql table the format must be YYYY-mm-dd Hour:min:sec, in order to be place in datetime field. But if you use the field type as varchar you don't need to care about format. you can insert in whatever format you wish.
Or you can rely on MySQL parsing:
SELECT STR_TO_DATE('12/16/2012 02:53', '%m/%d/%Y %H:%i')
Note: this expects two-digit month, day and hour, i.e. 01 - not 1.
See MySQL Date format for other formats.
Also for this approach to be of practical use you will have to process failed parsing attempts: for example, you can make your Datetime column NOT NULL so that all inserts or updates fail if you tried to write NULL into it (STR_TO_DATE will return NULL for invalid date)
You asked for an example, which no one has supplied yet, so here it is:-
$start_date = date("Y-m-d H:i:s", strtotime("12/16/2012 02:53"));
echo $start_date;
Output:-
2012-12-16 02:53:00
This format matches the MySql DateTime type.
See working example here which also demonstrates that it works in PHP 5.2.
See the manual for strtotime and date.
You can use strtotime(). It parses dates according to the format. For instance dates using / (MM/DD/YYYY) are parsed using the American format, and dates using - or . (DD-MM-YYYY or DD.MM.YYYY) are parsed using the European format. See the third note in the documentation.
You really should look at upgrading to 5.4 if at all possible. There you can use the really nice date classes.
I'm building a website with php and i'm using the DATE-type in my MYSQL table to store dates. The problem that i have is that this stores the dates by default in the format YYYY-MM-DD. But i need this format DD-MM-YYYY to appear on my PHP page with the possibility of calculating the amount of days between 2 different dates. How can this be achieved?
That's a display problem. Use mysql's date_format() function to convert to whatever your display requirements are, e.g.
SELECT date_format(datefield, '%d-%m-%Y'), ...
You can use strtotime to convert a string representation of the date to an actual date object in php, then use the date function to spit out the date as any string format you wish. Also, you can be strtotime to perform date calculations. Additional information can be found at this blog post.
$phpDate = strtotime($stringDateFromDb);
date('d-m-y', $dateFromDb);
strtotime('-3 days', strtotime($stringDateFromDb));
Here is an example for a way to do it:
$date_str = '2012-05-20'; //you get it from db
$date_now = strtotime($date_str); //convert it to unix timestamp
$yesterday=$date_now-24*60*60; //make calculations
echo 'yesterday was: '. date('d-m-Y',$yesterday); //date() returns the date in format you need
Further example here: How to calculate the difference between two dates using PHP?
In my php application I have this code:
<?php echo date("d/m/ Y ",strtotime($row["m_date"]));?>
In it, $row["m_date"] is fetching from a database.
The problem is that all the dates are printing perfectly except 27/2/2011. It's printing 1/1/1970 instead.
The date in the database is fine, and prints correctly in a PDF.
I'll assume you're getting the date from the database as the string 27/2/2011 because that's most probably what happens (correct me if I'm wrong).
PHP considers the string 27/2/2011 as being in the m/d/Y format, not d/m/Y and tries to parse under that assumption. Because the date is not valid under that format strtotime returns false. Giving false as the timestamp parameter to date is taken as 0, which is the timestamp for January 1st 1970.
What you need to do is either get your date in another format (or better still, as a timestamp) from the database, or parse it yourself (say using explode).
Good luck,
Alin
The database should be able to return the date to you as a UNIX timestamp. For example, MySQL has the UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(date_column) FROM table;
Postgres has date_part
SELECT DATE_PART('epoch', date_column) FROM table;
Most other databases should have similar features. If you can get the date out as a UNIX time stamp you can pass that directly to date() without having to use strtotime() as well.
All of this does of course assume you're using a temporal datatype for the columns in question (timestamp, datetime, timestamp with time zone, etc) and not just storing a string. You are using a temporal type, right? If not, then why not?
if you are storing the date in the database as a timestamp this should work
<?php echo date("d/m/Y",$row["m_date"]);?>
if you are storing the date in the database as a date or datetime this should work
<?php echo date("d/m/Y",strtotime($row["m_date"]));?>
How is the m_date stored in the databases? Is it a datetime object? Or a string.
Problem with strtotime is that it isn't real good at deciphering written dates. So something like 27/2/2011 gives problems while 27/02/2011 gives no problems at all.
So there are 2 solutions:
Make sure all the dates that get entered into the database are of the correct format (dd/mm/yyyy).
Write a regular expression that adds a leading zero to all single characters.
I have a mysql table field set as time type which stores data in the HH:mm:ss format. So when I list the data, it prints as, for example, 16:30:00. But I want to display hh:mm part only (not the seconds).
In case of datetime types, I can do date('H:i', '2010-03-16 16:30:00'). I mean I can retrieve any part. I wonder if there is any similar way like this for time only fields??
Please see, I can manipulate the time string to get rid of seconds in time part using str_replace, explode etc, I just wonder if there is any standard function there which I am not aware of.
If you want to do this with PHP, you'd have to get a timestamp from the time first, e.g.
echo date('H:i', strtotime('16:30:00'));
will output 16:30. Strtotime will assume the time is for the current date then.
You can let MySQL return the data in the format you want using Date_Format()
edit: as fireeyedboy pointed out there's also a TIME_FORMAT() function.
Another approach is:
SELECT UNIX_TIMESTAMP(time_field) AS tstamp FROM table;
Then you can use PHP's date() function to format it.
$time = date('H:i', $tstamp);