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.
Related
I am writing a program that sends emails to users when their subscription is about to expire so i have a table in my database with a date stored in varchar as 12th April 2018 I am using that format because it is easy to read therefore I don't have to convert it again later.. But when i write
$currentdate= Carbon::now()->toDateTimeString();
$threeDaystoExpire =Carbon::now()->addDays(130)->toDateTimeString();
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get a blank return output but when i change expires_on to created_at that is formatted like this 2018-04-12 12:41:36 I get the correct output. I tried changing the format of $currentdate and $threeDaystoExpireto match the data in my database as advised by previous threads i read and tried again like this
$currentdate= Date('dS F Y', strtotime(Carbon::now()->toDateTimeString()));
$threeDaystoExpire =Date('dS F Y', strtotime(Carbon::now()->addDays(130)->toDateTimeString()));
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get the same empty output. I am currently stuck. All the posts I've read only uses one value so they just make a statement to return just the date, convert it to a timestamp format then compare. I have hundreds of those date and I cant write a statement for each one so any help to tackle this problem will be greatly appreciated.
The toDateTimeString() method converts the Carbon DateTime object into a specific format such as 1975-12-25 14:15:16 which simply isn't a match for your varchar field.
Try using the Carbon API to convert Now to the format you need...
$currentdate = Carbon::now()->format('dS F Y');
$threeDaystoExpire = Carbon::now()->addDays(130)->format('dS F Y');
I'll also point out that the comparison will look at the day first, then the string value of the month, then the numerical year. This will give you very odd results. I might recommend strtotime on the output of your varchar field and use that instead instead of the other way around.
Do yourself a favor and store dates as YYYY-MM-DD (in a date column), it will make your life much easier. It's also easy to read and has been the standard format for ages (for good reasons).
The format you choose for your frontend is a different matter. You can maybe use an accessor for that.
I made a separate field to store the date in a human readable format so I don't have to convert it later in my app, then stored the timestamp format of the same date in a separate field to handle the calculations. It is way easier to use, read and saves me the stress of converting from timestamp then later reconverting back to timestamp which doesn't make sense.
As advised here to leverage platform tools more. I decided that data that will be used in different forms will be stored in a general format and i will allow the platform handle how they want to represent those data.
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'm having trouble getting the date to be imported into mysql from my form.
my form is validated so that the input will always be dd/mm/yyyy
i'm currently using
$date = date('Y/m/d', strtotime($_POST['night_attending']));
this takes the value from the form and assigns it the year/month/day
the problem is that its reading my form as mm/dd/yyyy
i can swap the code to 'Y/d/m' which will put it into my database the right way round but it will stop working if the day is past the 12th as it still believes that it is the month
i have tried using
date_default_timezone_set('Europe/Dublin');
and
date_default_timezone_set('Europe/London');
but it makes no difference
i'm contemplating just using the mm/dd/yyyy format on my form, but this isn't great as it's a uk site.
has anybody encountered this problem? i'm sure it must be comman and there must be a simple answer that i'm missing.
thanks
alsweet
There is no means to set MySQL's date format - the options exist, but they aren't enforced/used.
I don't recommend storing the dates as VARCHAR in order to maintain your format -- use the MySQL format, and work with MySQL date functions (IE: STR_TO_DATE, DATE_FORMAT) to output the format you want for screen.
Be aware that dates will be dependent on the timezone of the host MySQL is on - you might want to consider using epoch timestamps instead, depending on your needs.
This will give you the mysql date format from UK date.
$timestamp = strtotime(str_replace('/', '.', '03/04/2011'));
$mysql_date = date('Y-m-d', $timestamp); // 2011-04-03
You can use strptime() to parse the date:
$dateArray = strptime('%m/%d/%Y');
or date_parse_from_format() on PHP 5.3.
EDIT: I saw this too in the comments for strtotime, might help.
I have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.
I want to store dates in mysql so I set the table to be of type 'Date', which is fine but mysql requires that the full date is provided YYYY-MM-DD.
However some of my data does not include day and some is missing the month. Now I could just use a varchar(10) field, but then its difficult to run date based queries on the data.
Is there another date format which is not as strong and would allow me to use ?? or 00 where the day/month is not known?
Following from Babiker's answer, this is what the documentation says:
Ranges for the month and day specifiers begin with zero due to the fact that MySQL allows the storing of incomplete dates such as '2014-00-00'.
You can replace with zeros.