Convert number to date in PHP and format to YYYYMMDD [duplicate] - php

This question already has answers here:
PHP remove dots and hyphens
(5 answers)
Closed 3 years ago.
I want to convert date from, for example, 1441065600 to YYYYMMDD format. How do I do that?
$temp = date("Y-m-d",1441065600);
$rel_date = date_format( $temp, "YYYYMMDD");
The code above gives an error:
date_format() expects parameter 1 to be DateTimeInterface

Using date()
Simply write:
<?php
echo date('Ymd', 1441065600);
Otherwise, using a DateTime instance:
Short
<?php
echo (new DateTime())->setTimestamp(1441065600)->format('Ymd');
Note: the setTimestamp() method do not takes a string as parameter! Otherwise, you may want to do so:
Long
<?php
$english = '1441065600';
$timestamp = strtotime($english);
$date = new DateTime($timestamp);
echo $date->format('Ymd'); // 20161214
Descriptions
strtotime() - Parse about any English textual datetime description into a Unix timestamp
DateTime - Representation of date and time
Note: I created a new DateTime instance from the UNIX timestamp, English textual representation may lead to an error.
Other formats
I recommend you to read the DateTime::format() method documentation along with the date() function documentation to learn more about date formats.

$date = (new DateTime())->setTimestamp(1441065600);
echo $date->format('Ymd');

date_format is function in which first argument should be DateTime object, date function return string.
So first You need to create correct object.
$date = new DateTime(strtotime(1441065600));
and then format it with date_format
echo date_format($date,'Ydm');

You can pass the timestamp to the DateTime constructor by prepending # character:
$d = new DateTime('#1441065600');
echo $d->format("Ymd");
See Compound Formats.

Use Date function in PHP
echo $temp = date("Y-m-d",1441065600);
Result:
2015-09-01
Refer http://php.net/manual/en/function.date.php

Related

How to get the result of difference between two date using php? [duplicate]

This question already has answers here:
How to get time difference in minutes in PHP
(21 answers)
Closed 5 years ago.
I have this php code
$today_date = date('d/m/Y H:i:s');
$Expierdate = '09/06/2017 21:45:03';
$remaindate = date_diff($today_date,$Expierdate);
echo $remaindate;
and i need result from difference between two date.
date_diff() needs a DateTimeInterface as an argument. In other words, you need to create a DateTime object first, using new DateTime() as shown below.
$today_date = new DateTime();
$Expierdate = new DateTime('09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Live demo
The above would output
90 days
Because today is June 8th, and the format 09/06/2017 is September 6th - because you're using American format (MM/DD/YYYY).
If you ment June 9th (tomorrow), you need to use European format (MM-DD-YYYY, note the dash instead of slash). You can alternatively use DateTime::createFromFormat() to create from a set format, so your current format, 09/06/2017, is interpreted as June 9th. The code would then be
$today_date = new DateTime();
$Expierdate = DateTime::createFromFormat('d/m/Y H:i:s', '09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Output (live demo)
1 days
In any case, $remaindate holds some properties which can be used (see the manual), or you can format it to your liking by supplying the desired formation into the format() method.
new DateTime()
DateTime::diff()
DateTime::format()
DateTime::create_from_format()

Convert dd/mm/yyyy to yyyy-mm-dd in php [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I need to convert date format in php , But i am getting getting error
here is my code
$test = new DateTime('23/09/2016');
echo date_format($test, 'Y-m-d');
But i am getting error as
Message: DateTime::__construct(): Failed to parse time string (23/09/2016) at position 0 (2): Unexpected character
How to resolve the issue
You're not telling DateTime that what's your string date format. So, it's unable to create a DateTime object.
This should work :
$test = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($test, 'Y-m-d');
Read more about createFromFormat here.
Use createFromFormat instead. Like this,
$date = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($date, 'Y-m-d');
It's throwing exception because it's unable to parse String to date with / in it.
http://php.net/manual/en/datetime.createfromformat.php
You are getting error because your code is not match with Years and Day.
If you write code below it will work.I just exchange between Years and days .
$test = new DateTime('2016/09/23');
echo date_format($test, 'Y-m-d');
Or you can use createFromFormat to format first date string then convert it in your required format.
$input = "23/09/2016";
$arr = explode("/", $input);
# mktime is a function to create timestamp
# mktime (hour, min, sec, month, day, year)
$mktime = mktime(0,0,0,(int) $arr[1],(int)$arr[0],(int)$arr[2]);
$date1 = date ('d/m/Y', $mktime);
$date2 = date ('Y/m/d', $mktime);
echo "input: $input\ndate1: $date1\ndate2: $date2\n";
or you can try this one, $date2 is the final result.

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

Extracting Usable Info From datetime field in php/MySQL

I am trying to format a datetime variable with the following code:
$passed_time = $stu_quiz->c_date_time;
$passed_time_string = date_format($passed_time, 'M-d-Y');
For some reason, if I print $passed_time_string, the output is blank, but if I print out $passed_time, I get the date (in the format 2011-06-15 21:43:09).
Why is the date_format method not working?
The date_format function expects a "DateTime" object that is created using date_create.
Example:
$passed_time = date_create($stu_quiz->c_date_time);
$passed_time_string = date_format($passed_time, 'M-d-Y');
You are looking for just date()
http://php.net/manual/en/function.date.php
If you don't have PHP 5.3 and cannot use the DateTime class, try this:
$passed_time_string = date("M-d-Y", strtotime($passed_time));
First it converts your original MySQL time to a unix timestamp, then formats it as M-d-Y

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