How to make a datetime a bigint? - php

I want to convert a datetime to big int. For Example. I have an entry in the file that i read in php like normal datetime, "2021/05/20 11:46"(i keep it in a variable named $data) that i want to transform into a bigint like 202105201146 (year+month+day+hour+minute) . I tried to work around and make it working, but I still get the error :
"Argument #2 ($timestamp) must be of type ?int, string given in". >
The line in question is :
$ID= date('Y', $data) . date('m', $data) . date('d', $data). date('G', $data) . date('i', $data). date('s', $data);

You must first convert it into a datetime object, and then format it as "bigint":
$dateAsString = '2021/05/20 11:46';
$datetime = \DateTime::createFromFormat('Y/m/d h:i', $dateAsString);
echo $datetime->format('Ymdhi'); // 202105201146
However, since the error is asking for a timestamp (as int value), it could be better to use the getTimestamp() method of DateTime class, which returns the epoch timestamp:
$dateAsString = '2021/05/20 11:46';
$datetime = \DateTime::createFromFormat('Y/m/d h:i', $dateAsString);
$timestamp = $datetime->getTimestamp(); // 1621511160

Related

If a Date exist return a calculated date

I have the code below to add days to a date.
$date = '[[lbc_dates_lbc_date]]';
$date = date('d F y', strtotime('+28 days', strtotime($date)));
echo $date;
This works perfectly for cases where a date entry actually exists, however, it's displaying an odd date for cases where date entry doesn't exist yet (blank).
Can you amend the code to say if a date exists add days, otherwise leave blank?
Please see image attached (errors in red, correct view in green)
Thanks
strtotime() will return FALSE when it can't parse the date. This is being treated as 0, the epoch time, when you use it as the base time in the second call to strtotime().
Check for that before trying to use the result.
$parsed = strtotime($date);
if ($parsed) {
$date = date('d F y', strtotime('+28 days', $parsed));
} else {
$date = '';
}
You should use DateTime object for storing and manipulating dates.
echo $date !== null ? (new DateTime($date))->add(new DateInterval('P28D'))->format('Your date format here') : '';
https://www.php.net/manual/en/class.datetime.php
Basically it uses a ternary operator to check if $date is null, if it's not, it creates a new DateTime object for the current date, adds 28 days and echoes it in a chosen format. If $date is null, it will just echo an empty string - ''.
Edit: The above is just an one-liner example, a good practice would be getting it into a function.

Saving Carbon from string to MySQL

I'm having trouble saving a timestamp to my MySQL database. In this case, the user writes a date in a text field, with the format dd/mm/yyyy, and I want it to be saved as a timestamp.
The problem is, it is always complaining about incorrect format.
So far, I've tried:
$d = DateTime::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");
// or
$d = Carbon::parse($request['b_date']);
// or
$d = Carbon::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");
// so that I can
$p->b_date = $d;
But it never lets me save it.
Here's the log:
[2019-05-29 15:14:02] local.ERROR: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1111-11-11 00:00:00' for column 'b_date' at row 1 ...
I've been trying to do this for hours. What am I missing?
And how can '1111-11-11 00:00:00' be an invalid datetime value?
Declaring the datatype as DateTime in the migrations script worked for me.
...
Schema::create(...
$table->dateTime('b_date'); // use dateTime instead of timestamp
...
Setting it with carbon in the controller:
...
$p->b_date = Carbon::createFromFormat("d/m/Y H:i:s", $input['b_date'] . " 00:00:00");
...

How to add time of timeType to DateTimeType

I want to add variable of type TimeType to a variable of DateTimeType
I have triying this code :
$newDate = $dateAppointment->add($duration);
but i got this error
Warning: DateTime::add() expects parameter 1 to be DateInterval,
object given
Examples of data:
$dateAppountment = 2019-03-21 10:15:00
$duration : 00:15:00
I suppose there's some kind of transformer already exists in symfony, but I can't find it. So, here's a custom code how to convert time from DateTime to DateInterval and add it to another \DateTime:
$dateAppointment = (new \DateTime());
$dtDuration = (new \DateTime())->setTime(1, 15, 0);
$duration = $duration->format('\P\TH\Hi\Ms\S');
$newDate = $dateAppointment->add(new \DateInterval($duration));
Fiddle: https://3v4l.org/5lFlQ
Here is an example:
$duration = '1970-01-01 01:00:00.000000';
$timeObject = DateTime::createFromFormat('Y-m-d H:i:s.u', $duration, new DateTimeZone('UTC'));
$date = '2019-03-21 10:15:00';
$dateObject = DateTime::createFromFormat('Y-m-d H:i:s', $date);
$modify = '+' . $timeObject->format('U') . ' second';
echo $dateObject->modify($modify)->format('Y-m-d H:i:s');
Just get the seconds from your duration object and add them to your date object. If you used modify, there are a lot of things you can do.

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

Call to a member function format() on a non-object DateTime

This problem might be common but it seems like I can't find out what I did wrong.
I have two variables the date and time from database which I think is in UTC format and I need to convert to AEST;
$date = message['date']; //25/09/2014
$time = message['time']; //9:00:00
$combined_time = $date . " " . $time;
$schedule_date = DateTime::createFromFormat("Y-m-d H:i:s",$combined_time ,new DateTimeZone("Australia/Melbourne"));
return $schedule_date->format("jS-A-Y H:i:s T");
I got Call to a member function format() on a non-object exception.
You should use ("d/m/Y h:i:s"):
$schedule_date = DateTime::createFromFormat("d/m/Y h:i:s", $combined_time , new DateTimeZone("Australia/Melbourne"));
The given format is wrong because your date-time is as 25/09/2014 9:00:00. Check this example.
You are not creating any object of class so giving you error you need to create class object or use directly.
$schedule_date = new DateTime($date);
return $schedule_date->format("jS-A-Y H:i:s T");
or you need to pass correct format in Datetime() see #The Alpha answer for this
For more read manual :- http://php.net/manual/en/datetime.createfromformat.php
// convert string to timestamp
$timeStamp = strtotime($combined_time);
// create DateTime object use timestamp
$date = new DateTime();
$date->setTimestamp($timeStamp);
Then you can use $date->format('Y') to get year...

Categories