Date formation in viewmanager php - 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

Related

Replace first two characters of a string in php

I am dealing with a problem of time conversion from 12 hr format to 24 hour format.
Is there any single function in php to replace the first two characters of a string?
str_replace can be used only when I know the substring content to be replaced.
$str_to_replace = '12';
$input_str = 'ab345678';
$output_str = $str_to_replace . substr($input_str, 2);
echo $output_str;
"12345678"
If the date is always given in a specific format you could try to convert it to a DateTime object and format the output.
$dateString = '15-Feb-2009 2:24 PM';
$date = DateTime::createFromFormat('j-M-Y g:i A', $dateString);
echo $date->format('Y-m-d G:i'); // will show "2009-02-15 14:24"
In general you should try in avoid holding a date in a string. Convert it to a DateTime -- this makes it also easier for you to manipulate the object (e.g. move date +1 day)

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));

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

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