date( ) returns 1970-01-01 - php

I am using a jquery datepicker with the following format mm/dd/yyyy but I need it to be yyyy-mm-dd for the sql db so I am using this.
$date = date("Y-m-d",strtotime($startdate));
with the following
$query = "INSERT INTO complete_table ( name, startdate) VALUES ('$_POST[name]', '$date')";
Unfortunately I register 1970-01-01 in the db regardless of what the input is.
Any idea on what I am doing wrong? Thank you so much for the help.

When you get 1970-01-01 back from date() it means that the timestamp is incorrect. That date is the UNIX epoch.
When it comes to Javascript (in this case a datepicker) you should always make sure that what you get is, in fact, what you expect it to be. Simply passing it through strtotime() will cause problems like the one you have here.
One good way to handle dates is using the datetime extension. It has a static method, DateTime::createFromFormat, that will let you parse any date using any format:
// The value from the datepicker
$dpValue = '12/30/2013';
// Parse a date using a user-defined format
$date = DateTime::createFromFormat('d/m/Y', $dpValue);
// If the above returns false then the date
// is not formatted correctly
if ($date === false) {
header('HTTP/1.0 400 Bad Request');
die('Invalid date from datepicker!')
}
// Using the parsed date we can create a
// new one with a formatting of out choosing
$forSQL = $date->format('Y-m-d');
// ...

put dateformat in jquery when initializing the datepicker like
$( "#id/.class" ).datepicker({dateFormat: 'yy-mm-dd'});
This format will insert on mysql db(done on client side), otherwise format it on the server side code.

$startdate is invalid and therefor the strtotime function returns anything below 86400 (most likely 0), which is the amount of seconds in one day. Please refer to the PHP documentation for the right formatting of $startdate here.

It is called the epoch. So startdate is zero.

Related

PHP: how to create date before the Epoch (1970) using Date instead of DateTime?

In my PHP script I've got a function handling birthdays like so:
$dateTime = \DateTime::createFromFormat('U', $time);
The problem is that this returns false with negative $time numbers (i.e. dates before 1-1-1970). In the PHP docs there's a comment saying that indeed
Note that the U option does not support negative timestamps (before
1970). You have to use date for that.
I'm unsure of how to use Date to get the same result as DateTime::createFromFormat() gives though. Does anybody have a tip on how to do this?
If you just need to format a UNIX timestamp as a readable date, date is simple to use:
// make sure to date_default_timezome_set() the timezone you want to format it in
echo date('Y-m-d H:i:s', -12345);
If you want to create a DateTime instance from a negative UNIX timestamp, you can use this form of the regular constructor:
$datetime = new DateTime('#-12345');

Convert "m/d/y" date from a form text input field to a mysql datetime "friendly" input?

So I have a problem. Trying to convert input from form text input field which is in the following format: 08/06/2013 to a value that can be inserted into mysql datetime column.
I have tried this
$startdate_timestamp = strtotime($this->startdate);
// $this->startdate is the value from the input field
$this->startdate = date("YYYY-MM-DD HH:MM:SS",$startdate_timestamp);
But it seems that it is not doing anything. Is there any other way than this that would work ? I am using Yii framework so that is why code looks weird :)
strtotime() is smart, but it's not psychic or a genius, and when it screws up, it screws up bigtime. Don't use it, especially with ambiguous formats like m/d/y. There's no guarantee it won't be treated as as d/m/y.
Use date_create_from_format() instead, which lets you explicitly specify the input format. This is far more reliable, since you'll be in control over how the d and m portions are handled:
$ts = date_create_from_format('m/d/Y', '08/06/2013');
$start_date = $ts->format('Y-m-d H:i:s');
Do it on insertion using MySQL query superpowers. PHP date functions are a PITA: INSERT INTO FOO (date_field) values (DATE_FORMAT($this->startdate, '%Y %M %D')); Hope that helps!
$this->startdate = date("Y-m-d H:i:s", strtotime($this->startdate));
This will put it in the YYYY-MM-DD HH:MM:SS format compatible with MYSQL.

Format datetime from input string

I'm doing a date search filter where I have my date displayed as "j.n.Y G:i (26.6.2012 15:22)".
A user can enter the whole date or only a portion of it: "26.6","6.2012","6","15:22" are all valid inputs. Because I need to check this date in the database the format needs to be changed to the one of the database. For that I use:
$datum = '25.6.2012';
$date = DateTime::createFromFormat('j.n.Y',$datum);
echo $date->format('Y-m-d H:i');
Where I get an error if $datum is not in the format j.n.Y (if I only enter j.n or one of the above mentioned string portions i get an error).
A problem is also, for the entered string 'j.n.Y', i get the right output of the date, which also has the current time added to the date string (which was not in the initial date string). Example: I enter "22.6.2012", then I get the output "2012-06-22 15:33".
Can these two problems get fixed with existing php functions or should I make my own?
Help would be greatly appreciated.
You can list your acceptable data formats in an array, and loop around DateTime::createFromFormat() to see if any of the inputs produce an acceptable date:
$formats = array( 'j.n', 'j.n.Y');
$datum = '25.6.2012'; $date = false;
foreach( $formats as $format) {
$date = DateTime::createFromFormat( $format, $datum);
if( !($date === false)) break;
}
if( $date === false) {
echo "Invalid date!\n";
}
Finally, if you want to get rid of the current time in the newly created object and set the time to 00:00:00, just use the setTime() method on the date object:
// Sets the time to O hours, 0 minutes, 0 seconds
$date->setTime( 0, 0, 0);
For the first problem, you will need to write some code of your own because some of your acceptable inputs are not among the recognized input formats. Normalizing the input value will require you to fully parse it (a regular expression is a good way to start), and then you can call DateTime::createFromFormat without trouble.
For the second problem, putting an exclamation mark ! at the beginning of your format string would fix the time issue. From the documentation:
If format contains the character !, then portions of the generated
time not provided in format, as well as values to the left-hand side
of the !, will be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
However, since you are going to need to fully parse the input as mentioned above the matter is moot. Also note that the exclamation mark would cause missing values for year, month and day to use defaults that are probably undesirable.

CodeIgniter/JQuery/MySQL DateTime

Within my CodeIgniter app, I'm using a Jquery calendar pop-up that also captures time as set by the user, so the end result looks like: MM-DD-YYYY HH:MM, and I'm storing this in MySQL into a DateTime field that is: YYYY-MM-DD HH:MM:SS. What is the best (most efficient) way to push the date/time into MySQL so that it saves properly, and to pull is back out of MySQL and render it on the screen in the reverse format? Thanks!
Most efficient way is to use the ISO 8601 standard to pass date values between the client and server. Since the client and server talks in strings you'd be parsing the date to a string before sending it either way. The best format I prefer is the combined date and time in UTC:
2011-06-14T13:57Z
There are no spaces and it's clean. Then you'll have to parse it on the server side (should be relatively easy using PHP) and parse it on the client side.
For displaying purposes, I prefer to extend JavaScript's Date.prototype to include a format function that imitates PHP's date format.
Once you include the linked script from above you could do this on the server side -
var today = new Date();
alert(today.format('m-d-Y H:i')); //displays "06-14-2011 11:18"
Good luck!
I think you should use the strptime() function to parse the date received from the jQuery calendar your using and using mktime():
// Parse the time based on your jQuery calendar's format
$parts = strptime($calendar_value, '%m-%d-%Y %H:%M');
if ( ! empty($parts) )
{
// Create a Unix timestamp
$timestamp = mktime($parts['tm_hour'], $parts['tm_min'], 0, $parts['tm_mon'] + 1, $parts['tm_mday'], $parts['tm_year'] + 1900);
// Create a string representation of the Unix timestamp
$date = date(DATE_ISO8601, $timestamp);
}
You'll want to use $date to insert in your database. There is a function called "strtotime" which will attempts to parse dates that are in human-readable format but I doubt it's able to determine if the month or day comes first, especially if they're both lower than 12 which is why I chose to use "strptime" instead.
When you pull the data from MySQL, you can then simply use the date() and strtotime() function to populate the calendar:
echo date('m-d-Y h:i', strtotime($mysql_date));

PHP Zend date format

I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html

Categories