How to convert a Datetime string to standard mysql - php

I made a function in php to convert date and time coming from a txt to the mysql standard.
But she is turning the month wrong.
I have tried all these conversions but to no avail.
I would like your help because I don't know what else to do.
function convertstringdate('05/02/202116:43:49'){
$date = new DateTime($datetime);
return date_format($date, "Y-m-d H:i:s");
}
or
$input = '05/02/202116:43:49';
$date = strtotime($input);
echo date('Y-m-d H:i:s', $date);

Since you know the format of your datetime-string I suggest you use createFromFormat() like so:
$string = '05/02/202116:43:49';
$dateTime = DateTime::createFromFormat('d/m/YG:i:s', $string);
var_dump(date_format($dateTime, "Y-m-d H:i:s"));
// output: string(19) "2021-02-05 16:43:49"
Note that I am not sure if 05 or 02 is supposed to be the month in your example, so if this seems wrong to you you might just have to switch around d/m in the format string and make it m/d.
For explanation what character means what poriton of the datetime, see the linked above documentation reference.

Related

How to convert a PHP DateTime object to ISO string?

I have a date that I receive in MS format for JSON dates. It looks like this:
/Date(1365004652303)/
I can convert it to a PHP DateTime object by doing this:
$timestamp = round(((int) $originalMSdate) / 1000);
$convertedDate = new DateTime();
$convertedDate->setTimestamp($timestamp);
Ultimately, though, I need it to be a string in ISO 8601 format. I tried then converting it to an ISO date object & then converting that to a string with strval() but strval() doesn't work on date objects.
I've also tried
$dateString = date_format($convertedDate, 'YY-MM-DD H:i:s');
but I need it to also include timezone info, like this: 2015-10-01T21:22:57.057Z
I don't see characters for that in date_format.
How can I achieve this?
EDIT: I should clarify that I'm not printing the resulting string. I need to pass it to a field in a database that accepts a string datatype.
Please try the below code
<?php
// input
$time = microtime(true);
// Determining the microsecond fraction
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000);
// Creating DT object
$tz = new DateTimeZone("Etc/UTC");
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz);
$iso8601Date = sprintf(
"%s%03d%s",
$dt->format("Y-m-d\TH:i:s."),
floor($dt->format("u")/1000),
$dt->format("O")
);
// Formatting according to ISO 8601-extended
var_dump(
$iso8601Date
);
This worked:
$timestamp = round(((int) $originalMSdate) / 1000);
$dateString = date('c', $timestamp);
The format isn't EXACTLY the same. It's in this format:
2016-04-25T14:27:00-05:00 rather than
2016-04-25T14:27:00.057Z
but it's close enough that I can do some manipulation to get what I need.
this one is worked for me. For more please refer this article.
$date = date('Y-m-d H:m:s');
echo date('c', strtotime($date)); // 2020-04-08T16:04:56+05:30
echo date(DateTime::ISO8601, strtotime($date)); // 2020-04-08T16:04:56+0530
echo date(DateTime::ATOM, strtotime($date)); // 2020-04-08T16:04:56+05:30

PHP converting unknown datetime string to datetime object

I am having trouble with the following string which is supposed to be a datetime (response from an api).
2013-03-08T19:11:11.234+0000
I need to convert the string to ISO 8601.
The exact format should look like:
2016-03-01T12:00:00+00:00
If someone could help me do this in php would be great but I would be already more than happy if someone could identify the format (like yyyy-mm-ddThh:mm:ss).
It seems the API returns the time with milliseconds.
Try this:
$date = '2013-03-08T19:11:11.234+0000';
$format = 'Y-m-d\TH:i:s.uO';
$dt = DateTime::createFromFormat($format, $date);
echo $dt->format(DateTime::ISO8601);
Result:
2013-03-08T19:11:11+0000
EDIT
Based on comments on your answer, you need to convert such a time:
2016-03-01T11:01:51.126044 00:00
Since it's not possible to parse this format with DateTime, you need to make it readable first.
There are many ways to do this. What we need is to add a + before timezone, so that my code above work.
If you are sure the date you get from the API is always this format, and that there will always be only 1 space in the string, just replace the string with a space:
$date = '2016-03-01T11:01:51.126044 00:00';
str_replace(' ', '+', $date);
$format = 'Y-m-d\TH:i:s.uP';
$dt = DateTime::createFromFormat($format, $date);
echo $dt->format(DateTime::ISO8601);
This should work (note that here the timezone mask is P since there is a colon)
You can also use preg_replace() instead of DateTime, if you don't need the date for calculations:
$date = '2016-03-01T11:01:51.126044 00:00';
$date = preg_replace('`(\.[0-9]+\s)`', '+', $date);
echo $date;
This produces:
2016-03-01T11:01:51+00:00
If you need the date for calculation, just convert it to DateTime after:
$date = '2016-03-01T11:01:51.126044 00:00';
$date = preg_replace('`(\.[0-9]+\s)`', '+', $date);
$date = DateTime::createFromFormat(DateTime::ISO8601, $date);
var_dump($date);
This produces:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2016-03-01 11:01:51.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+00:00"
}
I suggest you to use Carbon: http://carbon.nesbot.com/docs/
echo Carbon::parse('2013-03-08T19:11:11.234+0000')->toAtomString();
Also, the format you want is ATOM, not ISO 8601. You could do #Arcesilas way, it should work too.

strtotime() doesn't recognize german shortform of date (dd.mm.YY)

I have much data with several timestamps and I just recognized that some are in "dd.mm.YYYY" which works very well with date("Y-m-d", strtotime($input)); but some are in "dd.mm.YY" and this does not work anymore - it always returns the current date.
My problem is that my data is too huge to fix this problem manually by editting. Is there any way to get the YYYY-mm-dd out of mm.dd.YY ?
Here you go...
$date = "20.02.71"; // sample date... (common German format)
$date = DateTime::createFromFormat('d.m.y', $date);
echo $date->format('Y-m-d');
will result in:
1971-02-20
Create a DateTime object, then format it to anything you want...
Well you can replace the . by -, you could do something like the following:
$date = str_replace(".", "-", "mm.dd.YY")
This would return
mm-dd-YY
You could use date_parse_from_format which would convert any formate into the formate you specify.
date_parse_from_format("y-m-d", $date);
It returns an array with very useful information like month, year etc.

Date function in PHP Not working properly

While converting date format from mm-dd-yy hh:ii:ss to yy-mm-dd hh:ii:ss format using below code.
<?php
echo $start_date = date("Y-m-d H:i:s",strtotime("10-14-2015 00:00:00"));
?>
But the result is
1970-01-01 05:30:00
If it is not a proper way to use date ,provide me alternate way
First check this answer whats the difference between dates over here and simply use str_replace like as
echo $start_date = date("Y-m-d H:i:s",strtotime(str_replace("-","/","10-14-2015 00:00:00")));
Or you can also use DateTime::createFromFormat over like as
$date = DateTime::createFromFormat("m-d-Y H:i:s","10-14-2015 00:00:00");
echo $date->format('Y-m-d');
Demo
Read the manual: http://php.net/manual/en/function.strtotime.php
and also specify your PHP version.
It has a nice example on checking if strtotime conversion was successfull:
if (($timestamp = strtotime($str)) === false) {
And this conversion is very critical, it supports only limited number of formats that should be specified very precisely in order days/months/years, and separators / or - or :
So you have to pick the format that you will support from following list:
http://php.net/manual/en/class.datetime.php
Be sure to create culturally aware code (e.g. US/UK/... format)
Please write your code as below:
echo $start_date = date("Y-m-d H:i:s",strtotime("10/14/2015 00:00:00"));

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php

Categories