Php crop time from date time string - php

I have a datetime string which I would like to crop the 'time' part out of.
I need to do some calculation on it so I need to convert it to Unix time stamp.
What I've tried:
Use substr, and then strtotime, but when checking the result back to a human readable time format, it is not the same as the original date.
function convert($dbTime){
$createDate = new DateTime($dbTime);
$strip = $createDate->format('Y-m-d');
$yearMonthDateArray = explode("-", $strip);
}
The explode here crashes.
Edit:
This is the value of dbTime: "2014-07-27 12:06:00"
I want it to be "2014-07-27", and then have strototime on this format. This does not work. Converting it back to human readable date it generates 2014-07-06
Regarding comments:
I have tried all sorts of datetime functions. They either crash or they don't return the proper time
Explode crashes - it doesn't continue to the next line of code.
Edit2:
This is what's going on next. This returns false
$timeWithMakeTime = mktime(0,0,0,(int)$yearMonthDateArray[0], (int)$yearMonthDateArray[1],(int)$yearMonthDateArray[2]);

Discarding all your messy code, I assume you just want this:
$dbTime = '2014-07-27 12:06:00';
$date = new DateTime($dbTime);
$date->setTime(0, 0, 0);
echo $date->getTimestamp();

DateTime is an object, so what if you want to get timestamp you can do is as follows:
function convert($dbTime){
$createDate = new DateTime($dbTime);
return $createDate->getTimestamp();
}
You can read more about getTimestamp and other DateTime functions
Make sure your variable $dbTime is in correct format. For example DateTime does not support split seconds.

$date = date('H:i:s', strtotime($dbTime));
echo $date;

Related

PHP - Difference between two times

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...
20180808180653
And this is a finisher time...
20180808180654
The difference between them is roughly 1 hour 24, but when i use...
date('h:i:s', $finshTime-$startTime)
I get 03:24:20 not 01:34:20.
Can someone please help?
The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).
$start = '20180808180653';
$end = '20180808180654';
$diff = $end - $start;
var_dump($diff); //1
$d = date('h:i:s', $$diff);
var_dump($d); //04:00:01
//the above is wrong. You need to try something like the code below
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));
I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.
Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.
First check if the type of $finshTime and $startTime are integer.
you can use get variable type:
gettype($startTime);
if this is the case try this with ():
$diff_date = date('h:i:s', ($finshTime - $startTime) );
if $startTime and $finshTime are string try this:
$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Date formation in viewmanager php

i'm very new to this Forum. I'm working on my own website and got a problem.
Because i'm very new to coding and not very skilled with php i can't find a solution for this little problem.
I would like to formate my date from the Database to a "friendlydate"
e.g. Date from Database: 2016-06-08 00:00:00
my wish-date: 08.06.2016
Here is my Code from the viewmanager, where i want do define the
"friendlydate"
// assign values to view object
$viewBlog->id = $value->id;
$viewBlog->bild = $value->bild;
$viewBlog->date = $value->date;
$viewBlog->author = $value->author;
$viewBlog->title = $value->title;
$viewBlog->text = $value->text;
$viewBlog->category_id = $value->category_id;
if (strlen($value->text) > 280) {$viewBlog->shorttext = substr($value->text,0,280)."...";} else {$viewBlog->shorttext = $value->text;}
***$viewBlog->friendlydate = here is my problem;***
$viewBlog->objCategory = $this->getViewCategory($value->category_id);
You can parse your original date in to a DateTime object which will then allow you to format the date however you like. For instance:
$date = new DateTime($value->wish-date);
$viewBlog->friendlydate = $date->format('Y-m-d H:i:s');
In this case, friendlydate would be 2016-06-08 00:00:00. To see how to specify what format you like see the documentation.
Assuming $viewBlog->friendlydate is your date variable,
$viewBlog->friendlydate = date("m.d.Y");
where m is numeric representation of a month, with leading zeros, n is numeric representation of a month without leading zeros and Y is a full numeric representation of a year output as 4 digits.
Using string functions:
$parts = explode('-', substr('2016-06-08 00:00:00', 0, 10));
$date = $parts[2].'.'.$parts[1].'.'.$parts[0];
This will convert the string as you have described. You may also want to look into PHP date functions.
You will just need to reformat your date. I am really fond of the DateTime method in php.
// Get the current date with its format
$date = DateTime::createFromFormat('Y-m-d H:i:s', $value->date);
// Convert it to a new format
$viewBlog->date = $date->format('d.m.Y');
In the resource below you can find information about different formats in which you can output your date.
Resources
DateTime - Manual

Convert User Submitted Date To UTC

I'm trying to figure out how to accept a date/time from a form, which is consequently in the user's timezone, and change it to UTC before inserting it into the database. For some reason, no amount of searching has netted me an answer.
My form will POST whatever date is selected by the user to my code, so I expect to be able to do something like this. Note: the $userDate may be relative to any number of timezones based on user's location
$userDate = $_POST['user_date'] // 2014-05-15 16:37:23
I anticipate using Date().getTimezoneOffset() on my form to also submit the users UTC offset (as detailed here).
$userOffset = $_POST['user_offset']
Then before inserting the date into my database, I would like to convert it to UTC -- but I am stumped on how to do that with PHP (I'm actually using Laravel so if you know of a way using Carbon, that would be even easier, but I couldn't find it in their docs).
I've been half tempted to manually parse the offset and convert it to number of seconds and add or subtract it to strtotime() output of the $userDate and then convert it back into a date format using date() -- but there has to be a better way!
What am I missing here? Does PHP have a function I just don't know about that lets me do something like:
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$utcDate = date_apply_offset($userDate, $userOffset);
echo $utcDate; // Outputs: 2014-05-15 20:37:23
Or am I making this harder than it has to be?
EDIT
Based on the solution provided by #vascowhite, I went with the following (added into question to improve answers for those seeking guidance)
I ended up using a function from moment.js since I was already using it to convert UTC to user's timezone on display.
HTML:
<input id="user_offset" type="hidden" name="user_offset" value="">
Javascript:
var offset = moment().format('ZZ');
$('#user_offset').val(offset);
PHP (in a custom date class):
class MyDate {
/**
* Convert Date to UTC
*
* #param string $date Any date parsable with strtotime()
* #param string $offset UTC offset of date
*/
public static function toUTC($date, $offset = '+0:00')
{
if ($timestamp = strtotime($date) && ! empty($offset) )
{
$newDate = date('Y-m-d H:i:s', $timestamp);
$newDate = new \DateTime($date . ' ' . $offset);
$newDate->setTimezone(new DateTimeZone('UTC'));
$date = $newDate->format('Y-m-d H:i:s');
}
return $date;
}
}
// To convert
$userDate = trim($_POST['user_offset']);
$userOffset = trim($_POST['user_date']);
$utc = MyDate::toUTC($userDate, $userOffset)
That class method isn't perfect, and in the event something goes wrong, it just returns the date back -- when really it should throw an exception.
This is a simple task with the DateTime classes:-
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$date = new \DateTime($userDate . ' ' . $userOffset);
var_dump($date);
$date->setTimezone(new \DateTimeZone('UTC'));
var_dump($date);
You can then format the date as you wish for output eg:-
echo $date->format('Y-m-d H:i:s');
or:-
$utcDate = $date->format('Y-m-d H:i:s');
echo $utcDate; // Outputs: 2014-05-15 20:37:23
See it working.
If you are doing any work with dates and times in PHP it is worth taking the time to become familiar with these extremely useful classes.
For all sorts of date/time manipulations you can make use of moment.php
For your example all what is needed are two lines of code:
$m = new \Moment\Moment('2014-05-15 16:37:23', '+0400');
echo $m->setTimezone('UTC')->format(); // 2014-05-15T12:37:23+0000
There is much more which helps to deal with date/time issues: https://github.com/fightbulc/moment.php
Cheers

How to return ISO date format in PHP for MongoDB?

I want to store the current date generated from PHP into MongoDB collection as an ISO date formate.
ISODate("2012-11-02T08:40:12.569Z")
However I am not able to generate such Kind of date in php which will be stored in MongoDB as an ISODate format.
This is what I ve done.
$d = new MongoDate(time());
echo $d;
and it is outputting something like,
0.00000000 1353305590
which is not the format I need. How to do this?
You could run the __toString function, or use the sec field
__toString will return a timestamp in usecs, which you can pass to date() after separating the seconds from milliseconds - read here: http://us1.php.net/manual/en/mongodate.tostring.php
OR, I personally prefer to have mongodb return just the seconds, which can be plugged directly into date() - read here: http://php.net/manual/en/class.mongodate.php
Also, if you're generating a MongoDate() for right now, you don't need to specify time();
In order to return an isodate, you need to do this:
echo date(DATE_ISO8601, (new MongoDate())->sec);
...
$exampleDate = new MongoDate();
echo date(DATE_ISO8601, $exampleDate->sec);
EDIT: To save your ISO date, you need to do the following:
$mongoDateObject = new MongoDate(strtotime("2012-11-02T08:40:12.569Z"));
For clarity, let's consider the following use case:
You need to convert a string in the simplified extended ISO 8601 format (e.g. returned by Javascript's Date.prototype.toISOString()) to and from PHP's MongoDate object, while preserving maximum precision during conversion.
In this format, the string is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset, as denoted by the suffix Z.
To keep milliseconds, we'll have to leverage PHP's DateTime object.
From string to MongoDate:
$stringDt = "2015-10-07T14:28:41.545Z";
Method 1 (using date_create_from_format):
$phpDt = date_create_from_format('Y-m-d\TH:i:s.uP', $stringDt);
$MongoDt = new \MongoDate($phpDt->getTimestamp(), $phpDt->format('u'));
Method 2 (using strtotime):
$MongoDt= new \MongoDate(strtotime ($stringDt),
1000*intval(substr($stringDt, -4, 3)) // cut msec portion, convert msec to usec
);
From MongoDate to string:
$MongoDt = new \MongoDate(); // let's take now for example
$stringDt =
substr(
(new \DateTime())
->setTimestamp($MongoDt->sec)
->setTimeZone(new \DateTimeZone('UTC'))
->format(\DateTime::ISO8601),
0, -5) // taking the beginning of DateTime::ISO8601-formatted string
.sprintf('.%03dZ', $MongoDt->usec / 1000); // adding msec portion, converting usec to msec
Hope this helps.
convert ISO date time in UTC date time here :
$timestamp = $quicky_created_date->__toString(); //ISO DATE Return form mongo database
$utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);
$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("d M Y", $time);
echo $dateInLocal; die;
You can convert ISODate time by using below code.
* return ISO-8601 date format:YYYY-MM-DD'T'HH:mm:ss.sssXXX , for example: 2015-09-07T10:13:45.110-07:00 .
*/
date("Y-m-d\TH:i:s.000P", strtotime($date));

Converting date to this format

I have a date in this format:
24-12-2010 // DAY - MONTH - YEAR
I need to get it in this format:
1995-12-31T23:59:59.999Z // The Z is for the TimeZone I think.
Check this link out:
http://lucene.apache.org/solr/api/org/apache/solr/schema/DateField.html
The above link is the way I need the date.
I am using PHP now, so this needs to be with PHP.
How can I convert these dates the easiest way?
Thanks
That is an ISO8601 format date; the following is what you want.
gmdate('Y-m-d\TH:i:s\Z', strtotime($date_value));
You can do something like that:
$dateTime = new DateTime($myDate);
$formatted = $dateTime->format("Y-m-d\TH:i:s.z\Z");
The mentioned solution with:
$dateTime->format(DateTime::W3C);
$dateTime->format(DateTime::ISO8601);
does return strings like:
2012-11-28T17:21:11+0100
which cannot be parsed, at least with newer Solr versions.
I wouldn't use gmdate if you need to support timezones. The DateTime implementation is well done, and is also available for functional programming.
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/ref.datetime.php
You can use the DateTime class
$dateTime = new DateTime();
$dateTime.setDate(24, 12, 2010);
$output = $dateTime.format(DateTime::W3C);
// Output now is your date in W3C format.
use the date ( string $format [, int $timestamp ] ) function of php!
In second paramter use http://php.net/manual/en/function.strtotime.php to get the timestamp from strings
$date = strtotime('24-12-2010');
$new_date = gmDate("Y-m-d\TH:i:s.z\Z",$date);

Categories