how to convert Integer values into timestamp format?

I have an Integer column “duration_temp” that have values represent the duration in minutes, I want to copy those values in another column “duration” of type timestamp, I’m having the problem of how to convert those Int minutes into timestamps format, for example:
if a value in Int is set to 4 then I should convert it to yyyy-mm-dd 00:04:00.
is there a function that can do that or close from doing that?any suggestion would be appreciate it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you have a duration in minutes. You could use DateInterval like this.

$yourDate = new DateTime('2021-01-01 00:00:00');
$durationInMinutes = 4;

$interval = new DateInterval("PT{$durationInMinutes}M");
$yourDate->add($interval);

echo $yourDate->format('Y-m-d H:i:s');

https://www.php.net/manual/en/dateinterval.construct.php

Method 2

If you mean that you just have minutes and want to make a timestamp from it with current date information, try this (after adding use CarbonCarbon; in top of you file):

$minutes = 4;
return Carbon::create(now()->year, now()->month, now()->day, 0, $minutes)->toDateTimeString();

Method 3

As your integer column duration_temp is in minutes, you have to convert it to seconds before you can get the expected result.

Take your example :

Int = 4 minutes => Int = 4 * 60 = 240 second

To finish :

date ("Y-m-d H:i:s", 240); // will give you 1970-01-01 00:04:00

Method 4

DateTime accepts extensive Relative Formats. This makes possible as an example:

$durationInMinutes = 67;

$date = date_create('2021-01-01 '.$durationInMinutes.' Minutes');
//or $date = new DateTime('2021-01-01 '.$durationInMinutes.' Minutes');

echo $date->format('Y-m-d H:i:s');
//2021-01-01 01:07:00

Also works correctly with negative minute numbers.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x