I need to save the value returned by the php "time();" function in a mysql table.
When I create an int field within a table, the maximum length of the int value is requested.
I wanted to ask you what value suggest to include in the type declaration of int.
I ask you this because, by saving the digit in int, it will be easy to compare it with other results of the "time ();" (which if I understand correctly, it always returns an int value).
Thank you
As of PHP manual:
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
So you're better of with using DATETIME type in your MySQL database and saving the timestamp after you convert it into valid format. For that I'd use DateTime. Even better if you just use new DateTime instead of time(), as DateTime takes time in constructor, which by default is now:
public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
If you were to use Doctrine 2, it would have been enough. Otherwise, you must format your DateTime object before inserting:
$dt = new DateTime();
$dt->format('Y-m-d H:i:s');
This will produce something like
2019-04-30 15:34:16
which is completely valid format for your DATETIME type in your mysql database.
If you need to compare other DateTime objects, you can always use DateTime::diff:
public DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
This will be enough for smart and representable operations with DateTimes and their comparison.
EDIT:
As you wrote
Ok, I converted the db field into a "DATETIME" field. But now I can't compare the result of the table field with a DateTime () object. Do you know how I can convert the table field to be comparable with a DateTime () object?
You need to create the DateTime object from the data you have in your database. It is achieved by using createFromFormat:
public static DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTime
So what you do is:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2019-04-30 15:34:16');
and voila!
Related
I'm trying to save events into my table that contain date_start and date_end timestamps. From another PHP page, I get four inputs: two date inputs and two time inputs. I'm trying to insert these values but I keep getting the following value on inserting it:
0000-00-00 00:00:00
Here's my script:
$rep=$bdd->query('SELECT * FROM association WHERE nom="'.$_SESSION['usertag'].'"');
$data=$rep->fetch();
$debut="\'".$_POST['date_start']." ".$_POST['time_start'].":00\'";
$fin="\'".$_POST['date_end']." ".$_POST['time_end'].":00\'";
$debut=date('Y-m-d H:i:s');
$fin=date('Y-m-d H:i:s');
$timestamp_debut =strtotime($debut);
$timestamp_fin = strtotime($fin);
$req=$bdd->query('INSERT into evenement values (NULL,'.$_POST['name'].','.$_POST['content'].',\''.$timestamp_debut.'\',\''.$timestamp_fin.'\','.$data['id'].')');
PHP's strtotime() outputs a Unix timestamp. If your database column type is DATETIME, a Unix timestamp is not the correct format. You can just insert the formatted date() string.
For example:
strtotime(date('Y-m-d H:i:s'))
1562117846
date('Y-m-d H:i:s')
2019-07-02 21:36:40
For MySQL:
MySQL recognizes DATETIME and TIMESTAMP values ... [a]s a string in either 'YYYY-MM-DD hh:mm:ss' or 'YY-MM-DD hh:mm:ss' format. A "relaxed" syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012#12#31 11^30^45' are equivalent.
String and Numeric Literals in Date and Time Context
However, it seems that you're using the current timestamp when you might want to use the values posted from your form. PHP's date() uses "the current time if no timestamp is given".
If you want to use your posted values instead, you can indeed use strtotime() to convert them to Unix timestamps and then date() to format them.
$date = '2019-07-02';
$time = '15:28';
date('Y-m-d H:i:s',strtotime($date.' '.$time));
2019-07-02 15:28:00
Alternatively, I might recommend using PHP's DateTime class:
$date = '2019-07-02';
$time = '15:28';
$datetime = new Datetime($date.' '.$time);
echo $datetime->format('Y-m-d H:i:s');
2019-07-02 15:28:00
I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)
Hello guys I 'm storing date in mongodb. The problem that I'm facing is that the date time string that I get. I try to convert it into mongodate but it converts it to 0.00000000 2016. Here is the code
$params['start'] = new MongoDate($params['start']);
$params['end'] = new MongoDate($params['end']);
The string bring the date time in this form 2016-04-07 19:49:50 but after the conversion it becomes like this 0.00000000 2016. Please tell me what is it that I'm doing wrong
Per the docs, MongoDate expects a timestamp value like 1460058590, not a string like 2016-04-07 19:49:50.
$params['start'] = new MongoDate(strtotime($params['start']));
The MongoDate constructor expects the time in Unix epoch seconds, not a time string.
public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
You'll need to convert your time string using strtotime or DateTime. The example code from the constructor documentation even includes an example:
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";
In my table, I have a variable $duration which is stored in minutes.
And I also have a time variable. Let it be $time1.
$time1=date('H:i:s',$time);
$duration=1000; //minutes
$time2= secondsToTime($duration*60);
I convert the $duration to time format using the function given below.
function secondsToTime($seconds) {
$dtF = new DateTime("#0");
$dtT = new DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h:%i:%s');
}
So in $time2, i have something like this stored 11:12:13
And in $time1 i have something like this stored 01:10:19
I want to perform $total=$time1+$time2;
So, I converted $time2 into time format.
$timeform= new DateTime($time2);
$newtime2= $timeform->format('H:i:s');
Now, I add $total=$time1+$newtime2;
But echo date('H:i:s',$total);gave me following error:
Notice: Object of class DateTime could not be converted to int
The second argument of date() should be a timestamp (i.e. an integer, i.e. seconds), not a formatted date string.
As far as I know only comparison operators work on datetime objects ($date1 > $date2), not math operators ($date1 + $date2).
See also http://nl3.php.net/manual/en/datetime.add.php and http://nl3.php.net/manual/en/datetime.modify.php
Use 1 datetime instance for calculating/formatting the total amount of time
Or, convert 2 datetime instances to seconds, add them, and format using date()
The second parameter of date() is expected to be a Unix timestamp as integer, not a DateTime object. (see php.net)
You need to convert your DateTime object into a Unix timestamp.
Try getTimestamp():
echo date('H:i:s',$total->getTimestamp());
Is there a difference between using PHPs time() and using new MongoDate()?
I need to store created_at and updated_at dates for each documents in by mongoDB collection
so that I can query them by date (for example documents updated last week).
From what I can see time() and new MongoDate() produces the same result?
That's because time() is default for the MongoDate constructor, from the manual:
public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
You should use MongoDate objects to query MongoDB.
If you use the raw output of time(), you will store/query for an integer. When you use MongoDate, you will be using MongoDB's Date type which gives you some additional benefits.