I'm using Laravel 4 with PostgreSQL. I created PostgreSQL timestamp fields with a migration:
$table->dateTime('start_date');
I tried inserting a timestamp generated with strtotime and received an error:
Invalid datetime format: 7 ERROR: invalid input syntax for type timestamp: "1383321600"
Hacking around it works:
new MyModel(array('start_date' => DB::raw("to_timestamp($start_date)")));
It seems like there should be a better way. Laravel itself generates timestamps without issue for the created_at and updated_at automatically-populated dates.
You must convert whatever the outcome of your strtotime is to the MySQL format before trying to save it. You can do this using the date function.
Example
date('Y-m-d H:i:s', strtotime('some time'))
It seems that Unix timestamps created with strtotime aren't converted correctly, but true PHP DateTime objects work fine.
I switched to using date_create with the same arguments and I can insert it directly without using DB::raw.
Doc for strtotime() says
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp
In SQL databases generally, timestamp doesn't mean a Unix timestamp. In SQL, if you were going to insert a timestamp into a table using standard SQL, you'd do it like this.
-- Implicit use
insert into table_name (column_name)
values ('2013-01-01 08:00:00');
-- Explicit use
insert into table_name (column_name)
values (timestamp '2013-01-01 08:00:00');
Related
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 have what is most likely a very simple question.. I am designing a simple blogging system and I am trying to put the current date into the table where the blog post is stored whilst waiting for administrator approval. but the method I have used puts 0000-00-00 into the date column! What I am using is as follows:
$query = "INSERT INTO blogentry VALUES ('".$mnam."','".date('d-m-Y h:m:s') ."\n"."','".$mcom."','".$approve."')";
I am relatively new to php so stumble accross errors like this all the time... but I cant seem to google this one!
Thanks guys!
So the easiest way to do this is just let MySQL handle it with the NOW() function:
INSERT INTO blogentry VALUES( ..., NOW(), ... )
Another option is to use TIMESTAMPs by changing your table - set the column to type TIMESTAMP with DEFAULT CURRENT_TIMESTAMP, and you can just ignore that column when inserting - it will automatically be filled with the current time. You will need to specify the columns you're inserting to in order to skip a column:
INSERT INTO blogentry( column1, column2 ) VALUES( column1value, column2value )
Finally, you NEED to sanitize your inputs. Preferably using prepared statements and PDO (http://php.net/manual/en/pdo.prepared-statements.php), or at least using mysql_real_escape_string.
From the MySQL manual on DATE, DATETIME
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
This means you have to insert the dates in YYYY-MM-DD format. You are using date('d-m-Y h:m:s') format. Change that to date('Y-m-d') and it should insert correctly.
If you want the time as well, then you need to change the column datatype to DATETIME and then insert using the format date('Y-m-d H:i:s').
As other mention, you can use an INT column type instead and store a Unix timestamp which is stored in UTC so it is more portable. You can then easily manipulate the timestamp to output the date any way you would like.
Try just storing a strtotime() result. It creates a unique timestamp, which can then be parsed however you need it in the future.
You might need to give the timestamp to the date function:
date('d-m-Y h:m:s', strtotime('now'))
Also, to do a standard datetime format:
date('Y-m-d H:i:s', strtotime('now'))
I have a MYSQL table column of type timestamp and using CURRENT_TIMESTAMP as default when a new record is added.
The date field in my database table looks like this 2011-08-16 12:09:25 How is it possible to format that into MM/DD/YY to display on my site? I tried some functions from the date helper but I get errors.
note: I'm trying to figure out how to use Codeigniter functions for this, if possible.
In the CI manual there are examples with $timestamp = '1140153693'; but my database timestamp is a different format and get errors.
To display a timestamp, just use the PHP Date class. But since MySQL outputs timestamps as a string not an INT, you'll have to first convert the timestamp string to a timestamp INT using PHP's strtotime function. The code looks like this:
echo date("m/d/y",strtotime($timestamp));
Date
http://www.php.net/manual/en/function.date.php
StrToTime
http://php.net/manual/en/function.strtotime.php
Sorry, I didn't properly explain the issue but solved it.
In order to use the Codeigniter date functions I had to convert the mysql ISO 8601 date format to a 32-bit integer.
I had to do the following
$unix = mysql_to_unix($row->message_date); //conversion to string
$datestring = "%m/%d/%Y";
echo mdate($datestring, $unix);
I was using the ISO 8601 format and getting errors.
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 am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information?
MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data.
Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?
I would store the dates in the MS-SQL format to assist in using the date manipulation functions in T-SQL to their fullest. It's easier to write and read
SELECT * FROM Foo
WHERE DateDiff(d,field1,now()) < 1
Than to try and perform the equivalent operation by manipulating integers
To convert a MsSQL date into a unix timestamp use dateDiff:
SELECT DATEDIFF(s,'1970-01-01 00:00:00',fieldName) as fieldNameTS
FROM TableName
WHERE fieldName between '10/1/2008' and '10/31/2008'
To Convert an Unix Timestamp into a MsSQL Date, you can either do it in PHP:
$msSQLDate = date("Y-m-d H:i:s", $unixDate );
or in MsSQL
INSERT INTO TableName (
fieldName
) VALUES (
DATEADD(s,'1970-01-01 00:00:00', ? )
)
Where parameter one is int($unixDate)
I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME)
Just use "YYYY-MM-DD HH:MM:SS" for inserting in php: date('Y-m-d H:i:s', $myTimeStampInSeconds);
-edit in response to comments below here -
for selected columns you can use $timestamp = strtotime( $yourColumnValue );
i recommend storing in the databas native format because you can then use SQL to compare records using SQL date/time functions like DATEADD() etc.
Hello and good day for everyone
Yes , might be thats the best way , store dates in db, they will take db format and you can format when you need as you wich
But there is another one solution in the ISO-developed international date format, i mean ISO 8601.
The international format defined by ISO (ISO 8601) tries to address all date problems by defining a numerical date system as follows: YYYY-MM-DD where
YYYY is the year [all the digits, i.e. 2100]
MM is the month [01 (January) to 12 (December)]
DD is the day [01 to 31] depending on moths :P
Using numerical dates does have also some pitfalls with regard to readability and usability it is not perfect.But ISO date format is, however, the best choice for a date representation that is universally (and accurately) understandable.
Note that this format can also be used to represent precise date and time, with timezone information
Here is a detailed information about ISO 8601:2000
http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm
With no more....
Bye bye