How to parse date string to dateTime in php? - php

I have a date string in this format "2014-12-01 16:00:02,153". How do I parse this to a datetime format for mysql?
I am using laravel and Carbon. My code is Carbon::parse("2014-12-01 16:00:02,153");
but get an error that reads DateTime::__construct(): Failed to parse time string (2014-12-01 16:00:02,153) at position 20 (1): Unexpected character

You could use the createFromFormat method from the DateTime object :
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s,u', "2014-12-01 16:00:02,153");
echo $dateTime->format('Y-m-d H:i:s');

PHP is confused by the time format you are handing over.
new DateTime("2014-12-01 16:00:02,153"); // fails
strtotime("2014-12-01 16:00:02,153"); // fails
This is because of the unexpected part with the comma at the end. Where are you getting this strange timestamp with comma seperated milliseconds from? It is unusual.
As you are asking for datetime which usually does not need any milliseconds you can do the following:
$timeparts = explode(",","2014-12-01 16:00:02,153");
Carbon::parse($timeparts[0]); // should work
$timeparts[1] is the milliseconds then.
If you want to be more precise you can round the milliseconds:
if(intval($timeparts[1]) >= 500) {
// time +1 second
}
... or you treat the milliseconds seperatly if you need em. Add them to the generated timestamp later and check the docs of Carbon.

Related

The separation symbol could not be found Data missing

I'm working with Laravel 5.8 and I wanted to show a popup message if the UNIX timestamp of the current date is equal to the defined Unix timestamp of the popup.
So in order to do that, I added this at the Controller:
$date1= $popup->datep; // returns 1636403400
$date1 = Carbon::createFromFormat('Y-m-d H:i:s', $date1);
dd($date1);
But instead of getting the result of $date1, I get this error:
The separation symbol could not be found Data missing
So what's going wrong here? How can I solve this issue?
You are specifying a format that is clearly not an unix timestamp. Use method for the timestamp.
$date = Carbon::createFromTimestamp($popup->datep);
If you want to compare it to be the same date, you should do the following. I don't assume you want to compare it by the hour or second, that those will almost never match.
$date->startOfDay()->eq(now()->startOfDay());
Regarding Carbon Docs:
createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.
which is means that your second parameter must be a valid date/time format, not a timestamp.
The DateTime::create docs:
$datetime
String representing the time.
Instead, you need to use the createFromTimestamp instantiator.
$date1 = Carbon::createFromTimestamp($date1);

Parse date with 2-digit year

I want to parse a string of the form 02.01.19 13:49 with Carbon.
Now \Carbon\Carbon::parse('02.01.19 13:49'); fails with
DateTime::__construct(): Failed to parse time string (20.01.19 13:49)
at position 9 (1): Double time specification
Is there any way to tell Carbon that the 19 represents 2019?
This is how I managed to do it, buts its a bit ugly:
\Carbon\Carbon::parse(
preg_replace('/(\d\d\.\d\d\.)(\d\d) /','${1}20$2 ', '02.01.19 13:49')
);
You can use the method Carbon::createFromFormat() to create a carbon instance from a custom date format string.
Carbon\Carbon::createFromFormat('m.d.y H:i', '02.01.19 13:49');
You can reference the PHP date format string from http://php.net/manual/en/function.date.php
Carbon::createFromFormat("d.m.y H:i", "02.01.19 13:49");
This could solve the issue if the input format is fixed.

Convert MongoDB ISODate format to normal PHP readable date format [duplicate]

I spent 3 days trying to solve this with no success.
I'm using the MongoDB PHP Library and i'm trying to convert a timestamp in a valid date using the example in the PHP Docs but it's always returning 1970-01-17.
The code is:
$utcdatetime = new MongoDB\BSON\UTCDateTime(1453939200);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime);
The documentation states that the constructor takes in an integer parameter representing the timestamp in milliseconds, you are providing a timestamp in seconds hence the invalid date result.
Multiply the value by 1000 to get the timestamp in milliseconds thus return a valid datetime object converted:
$timestamp = 1453939200 * 1000;
$utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime);
To anyone looking for this:
You have first to convert the value in a timestamp and after that you will be able to convert it in a valid ISODate.
Eg:
$utcdatetime = new MongoDB\BSON\UTCDateTime(strtotime($date));
$date2 = new MongoDB\BSON\Timestamp(1, date($utcdatetime));

Carbon/DateTime: The timezone could not be found in the database

I'm reading a CSV file with datetime fields but when I try to convert the date to Carbon by doing $date = new Carbon($row['date']) I get one of these errors:
DateTime::__construct(): Failed to parse time string (09/07/2014 16:55:22 MEST) at position 20 (M): The timezone could not be found in the database
DateTime::__construct(): Failed to parse time string (24/01/2014 16:57:27 MET) at position 0 (2): Unexpected character
Seems PHP does not recognize the MET/MEST timezones. How can I dynamically convert any non-standard timezones to create a Carbon/DateTime object?
The format may not be in a recognizable format. Use this instead. It will only work with MET, as MEST is not a valid timezone
$date = Carbon::createFromFormat('d/m/Y H:i:s T', $row['date']);

How to format date in PHP from a string of concatenated numbers?

I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.

Categories