Convert time to integer in Php - php

How would you convert time to integer?
string(8) "04:04:07"
I want this as 4(hours) or much better 4.04(4hours and 4 minutes)
I tried
$yourdatetime = "04:04:07";
$timestamp = strtotime($yourdatetime);
Which results in
int(1458590887)

The date function is your friend:
Given your own code above:
$yourdatetime = "04:04:07";
$timestamp = strtotime($yourdatetime);
You can then feed it into the date function:
echo 'Hours:' . date('h', $timestamp); // Hours: 04
echo 'Minutes:' . date('i', $timestamp); // Minutes: 04
echo 'Seconds:' . date('s', $timestamp); // Seconds: 07
Refer to the docs for the specific format(s) you'd like for hours - there's many options.
You could even do it in one move:
echo date('h.i', $timestamp); // 04.04
If you need it truly numeric:
echo float(date('h.i', $timestamp)); // 4.04

Use (float) and preg_replace to one-line-code conversion:
$floatval = (float) preg_replace('/^(\d+):(\d+).+/','\1.\2',$yourdatetime);

So we'll break this out. If we cast the hours as an integer and leave the minutes as a string this is a pretty simple conversion
$time = explode(':', $yourdatetime);
$hours = (int)$time[0] . '.' . $time[1];
Avoids any overhead from regex

strtotime() returns the time in seconds since the Unix Epoch. You can then format this using date(). Documentation for date: http://php.net/manual/en/function.date.php
To get the number of hours (4):
$timestamp = date("g",strtotime($yourdatetime));
To get the number of hours and minutes (4.03):
$timestamp = date("g.i",strtotime($yourdatetime));

Related

How to create DateTime from a Unix timestamp with milliseconds? [duplicate]

I have this 13 digit timestamp 1443852054000 that i want to convert to date and time but dont succeed. I have tried this codes:
echo date('Y-m-d h:i:s',$item->timestamp);
doesnt work for me and also this
$unix_time = date('Ymdhis', strtotime($datetime ));
and this :
$item = strtotime($txn_row['appoint_date']);
<?php echo date("Y-m-d H:i:s", $time); ?>
what should i use?
This timestamp is in milliseconds, not in seconds. Divide it by 1000 and use date function:
echo date('Y-m-d h:i:s', $item->timestamp / 1000);
// e.g
echo date('Y-m-d h:i:s',1443852054000/1000);
// shows 2015-10-03 02:00:54
A 13 digit timestamp is used in JavaScript to represent time in milliseconds. In PHP 10 a digit timestamp is used to represent time in seconds. So divide by 1000 and round off to get 10 digits.
$timestamp = 1443852054000;
echo date('Y-m-d h:i:s', floor($timestamp / 1000));
You can achieve this with DateTime::createFromFormat.
Because you've a timestamp with 13 digits, you'll have to divide it by 1000, in order to use it with DateTime, i.e.:
$ts = 1443852054000 / 1000; // we're basically removing the last 3 zeros
$date = DateTime::createFromFormat("U", $ts)->format("Y-m-d h:i:s");
echo $date;
//2015-10-03 06:00:54
DEMO
http://sandbox.onlinephpfunctions.com/code/d0d01718e0fc02574b401e798aaa201137658acb
You may want to set the default timezone to avoid any warnings
date_default_timezone_set('Europe/Lisbon');
NOTE:
More about php date and time at php the right way

How to convert a 13 digit Unix Timestamp to Date and time?

I have this 13 digit timestamp 1443852054000 that i want to convert to date and time but dont succeed. I have tried this codes:
echo date('Y-m-d h:i:s',$item->timestamp);
doesnt work for me and also this
$unix_time = date('Ymdhis', strtotime($datetime ));
and this :
$item = strtotime($txn_row['appoint_date']);
<?php echo date("Y-m-d H:i:s", $time); ?>
what should i use?
This timestamp is in milliseconds, not in seconds. Divide it by 1000 and use date function:
echo date('Y-m-d h:i:s', $item->timestamp / 1000);
// e.g
echo date('Y-m-d h:i:s',1443852054000/1000);
// shows 2015-10-03 02:00:54
A 13 digit timestamp is used in JavaScript to represent time in milliseconds. In PHP 10 a digit timestamp is used to represent time in seconds. So divide by 1000 and round off to get 10 digits.
$timestamp = 1443852054000;
echo date('Y-m-d h:i:s', floor($timestamp / 1000));
You can achieve this with DateTime::createFromFormat.
Because you've a timestamp with 13 digits, you'll have to divide it by 1000, in order to use it with DateTime, i.e.:
$ts = 1443852054000 / 1000; // we're basically removing the last 3 zeros
$date = DateTime::createFromFormat("U", $ts)->format("Y-m-d h:i:s");
echo $date;
//2015-10-03 06:00:54
DEMO
http://sandbox.onlinephpfunctions.com/code/d0d01718e0fc02574b401e798aaa201137658acb
You may want to set the default timezone to avoid any warnings
date_default_timezone_set('Europe/Lisbon');
NOTE:
More about php date and time at php the right way

strtotime subtraction not working

I have this PHP code:
echo "time30: ".$time30.'<br />';
echo "time: ".$time.'<br />';
echo date("s",strtotime($time) - strtotime($time30));
Which is returning:
time30: 15/09/2015 20:27:16
time: 15/09/2015 21:08:41
00
Why is it not returning the difference instead of 00?!
Subtracting 2 timestamps doesn't get you a timestamp. It gets you the difference between them. You are then trying to read that difference as a timestamp (or an exact moment in time), and it just to happens to have a "seconds" value of 0.
If you want the number of seconds between these two times, then you just need to do:
echo strtotime($time) - strtotime($time30);
P.S. 15/09/2015 20:27:16 is not a format that strtotime recognizes. I suggest you use DateTime objects for this task.
$time = DateTime::createFromFormat('d/m/Y H:i:s', '15/09/2015 21:08:41');
$time30 = DateTime::createFromFormat('d/m/Y H:i:s', '15/09/2015 20:27:16');
$diff = $time->diff($time30);
$minutes = ($diff->days*24*60) + ($diff->h*60) + ($diff->i);
$seconds = ($minutes*60) + $diff->s;
echo $seconds; // 2485 (which is 41 minutes, 25 seconds)
instead of using
$time30= '15/09/2015 20:27:16';
$time= '15/09/2015 21:08:41';
use
$time30= '2015-09-15 20:27:16';
$time= '2015-09-15 21:08:41';
Format has to be correct http://php.net/manual/en/function.strtotime.php

PHP - Adding 7 days to a date the proper way [duplicate]

I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19

Add number of days to a date

I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19

Categories