My client has entered some start and end dates into our system and I want to be able to format it with PHP.
The values are 930 and 1530. Processing the 1530 variable is fine but its the 930 that returns false.
Here is my script so far but no success. Error returns bool(false) because it can't get a readable time (I believe?)
$time = DateTime::createFromFormat('Hi', $var);
$format = "H:i";
$result = $time->format($format);
That's because your initial time format is ambiguous. Assuming that you have time without leading zeros all the time one can do something like this:
$var = '930';
$time = DateTime::createFromFormat('Hi', str_pad($var, 4, '0', STR_PAD_LEFT));
$format = "H:i";
$result = $time->format($format);
I wouldn't bother with DateTime for this, split it and join it like this:
$var = 1530;
$minutes = substr($var, -2, 2);
$hours = str_replace($minutes, '', $var);
$time = $hours . ':' . $minutes;
Then use DateTime on the string:
$dateTime = new DateTime($time);
$time = $dateTime->format('H:i');
Related
I'm trying to find a way to make an strtotime with a provided datetime match up somewhat with a time generated from microtime(true).
I can't quite figure it out, I've tried dividing my strtotime by 1000 but this doesn't quite give me the right result, how can I match them up to be identical.
$time = strtotime('2022-04-06 09:00:00') / 1000;
$micro = microtime(true);
echo "$time - $micro";
output
1649260.8 - 1649233311.5081
You can do this just by adding a dot and zeros to your string :
$time = strtotime('2022-04-06 09:00:00');
$micro = microtime(true);
echo $time.".0000 - ".$micro;
Otherwise you can use the number_format function :
$time = strtotime('2022-04-06 09:00:00');
$timemicro = number_format($time, 4, '.', '');
$micro = microtime(true);
echo $timemicro." - ".$micro;
These are the simplest solutions I have found :)
I have a function where I pass total 5 parameters to it.
$Date1, $Time1, $Date2 and $Time2 and $Interval.
I first form a timestamp1 using Date1Time1, then form a timestamp2 using Date2Time2 , and then I divide these two timestamps into equal intervals of hours and then store into an associative array.
e.g.
$Date1 = 27-03-2016
$Time1 = 18:00
$Date2 = 27-03-2016
$Time2 = 21:00
Now I want to divide this time into equal time intervals of 60 mins, and then want to store into an associative array into below format.
$array = [27-03-2016 => 18:00 , 27-03-2016 => 19:00, 27-03-2016 => 20:00, 27-03-2016 => 21:00]
I have written below function in php. When I run this, the file is getting hanged forever and not responding anything and when I check the server logs then it gives
error: Maximum execution time of 30 seconds exceeded at line
$end_time = date('H-i',strtotime($end_timestamp));
As I am comparatively new to php, I am not able to understand what is going wrong.
function FindTimeSpan (&$Date1,&$Time1,&$Date2,&$Time2,&$Interval)
{
$timespan=array($Date1 => $Time1);
$timestamp1 = strtotime($Date1 . $Time1);
$timestamp2 = strtotime($Date2 . $Time2);
while( $Date1 < $Date2)
{
$start_timestamp = $timestamp1;
$end_timestamp = $timestamp2 . '+' .$Interval;
//Separating Date and Time from a timestamp
$end_date = date('Y-m-d',strtotime($end_timestamp));
$end_time = date('H-i',strtotime($end_timestamp));
//pushing value to an array
$timespan = array_merge($timespan, array($end_date => $end_time));
//setting the start value to the new end value
$timestamp1 = $end_timestamp;
}
echo 'timestamp array' . json_encode($timespan);
}
The problem you encounter is an infinite loop, which is caused by the condition $Date1 < $Date2 . You don't modify any of these two values, so the condition will always be true. Strangely, you don't use the different timestamp values that are modified, but you should.
Concerning that, you should replace $end_timestamp = $timestamp2 . '+' .$Interval; by simply $end_timestamp = $timestamp2 + $Interval ; . Using the single quotes and the point will make PHP think of this as a string operation instead of a mathematical operation. With this and using this loop condition $timestamp1 < $timestamp2, your code should stop.
As said in a comment, your array structure is impossible because you can't assign have the same key multiple times. Instead of this, you should create an array per date and pushing the different times to these arrays.
To do this, you should first fix the way you retrieve the date and time in the loop. In the following code, the call to strtotime is unnecessary as the function date requires a timestamp, so no need to convert this back to a string.
//Separating Date and Time from a timestamp
$end_date = date('Y-m-d',strtotime($end_timestamp));
$end_time = date('H-i',strtotime($end_timestamp));
You should also be consistent, the format used here for the date is not consistent with the format you gave as exemple.
Now as per your suggestions above, I have made few changes in my code as well as the requirement.
I have not decided to use Assoc array.
Instead I will divide the two stamps between equal timeintervals (assuming it is possible).
Then I am doing the simple array push of this string.
Later on once this array is form, I will parse it and take the Date and Time separate.
Now my code is not entering into infinite loop as I am comparing the two timestamps. But now, the issue is it is pushing the first value to the array but all the subsequent values are getting pushed as null
so the output I am getting from the below code is like
array[1459051200,null,null,null,......]
Below is the code
$Date1 = "2016-03-27";
$Time1 = "00:00";
$Date2 = "2016-03-30";
$Time2 = "22:00";
$Interval = '60';
FindTimeSpan ($Date1, $Time1, $Date2, $Time2, $Interval);
function FindTimeSpan (&$Date1,&$Time1,&$Date2,&$Time2,&$Interval)
{
$timestamp1 = strtotime($Date1 . $Time1);
$timespan=array();
array_push($timespan,$timestamp1);
echo 'Value of array timespan' . json_encode($timespan);
$timestamp2 = strtotime($Date2 . $Time2);
while( $timestamp1 < $timestamp2)
{
$start_timestamp = $timestamp1;
$end_timestamp = $timestamp1 + $Interval;
//pushing value to an array
array_push($timespan,$end_timespan);
//
$timestamp1 = $end_timestamp;
}
echo 'timestamp array' . json_encode($timespan);
}
I have a PHP Script that has an INT in the format MMSSMS - Minutes Seconds Milliseconds defined as $time. I just need a : every 2 places in $time. Any help is appreciated.
Example: $message = 'I clocked in (MM:SS:MS) '.$time.';
the issue is the $time displays as 000044 instead 00:00:44 on echo
This code replaces 2 consecutive digits not on the end of the string with the digits followed by colon
$message = 'I clocked in (MM:SS:MS) '.preg_replace('/\d{2}(?!$)/','$0:',$time);
php.net/preg_replace
demo: http://sandbox.onlinephpfunctions.com/code/de0ce1e4466ff747f1bba2ac92331623a1b234ed
<?php
$time = '123456';
$str = strval($v);
$time = $str[0].$str[1].":".$str[2].$str[3].":".$str[4].$str[5];
echo $time;
?>
Hope this helps:
$time = '001122';
$minutes = substr("$time", 0, 2);
$seconds = substr("$time", 2, 2);
$mills = substr("$time", 4, 2);
echo $newTime = "$minutes:$seconds:$mills";
You can use chunk_split() in conjunction with rtrim()
$time = '000044';
$time = rtrim(chunk_split($time, 2, ':'), ':');
Edit
If $time is an INT, you would need to convert using (string)$time or strval($time). However, in your example you are using 000044, so I am assuming $time is already a string...
I want to calculate the number of years between two dates. One of them is retrieved from the database while the other is taken from user input in date format.
I used this code to get the date from the user:
$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyaer = $_POST['to-year'];
$dateto = date("$toyaer-$tomonth-$today");
And here is how I calculated it with the one retrieved from the database,
$start = $leaveresult['date']; // i took from database
$end = strtotime($dateto);
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));
The problem is that the result I get is always 0.
I tried different methods but all of them resulted with 0 and one of them resulted with a huge number.
This is untested but I think something like this will work:
$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyear = $_POST['to-year'];
$dateto = "$toyear-$tomonth-$today";
$start = $leaveresult['date'];// i took from database
$end = strtotime($dateto);
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));
I am assuming $leaveresult['date'] is unix timestamp
Also please note that I fixed the post variable names.
If the start date is not in unix timestamp then use
$start = strtotime($leaveresult['date']);// i took from database
The DateTime class simplifies all this by giving you a diff method. This will return a DateInterval object which you can get the values you're looking for.
Assuming $_POST looks like this:
$_POST = array(
'to-year' => 2010,
'to-month' => 8,
'to-day' => 22
);
And $leaveresult['date'] looks like this:
$leaveresult = array(
'date' => date('Y-m-d H:i:s', strtotime('-5 years')));
You can do something like this...
$input_date = new DateTime(sprintf("%d-%d-%d", $_POST['to-year'], $_POST['to-month'], $_POST['to-day']));
$database_date = new DateTime($leaveresult['date']);
$diff = $database_date->diff($input_date);
echo $diff->format('%r%y years') . PHP_EOL;
echo $diff->format('%r%m months') . PHP_EOL;
echo $diff->format('%r%d days') . PHP_EOL;
$years = $diff->y;
Which will yield
3 years
1 months
5 days
And $years will equal 3
you need in both cases a timestamp - the one you formatted ( as date object ) and the one you get from the database...
so I think you'r approach wasn't wrong, if your getting timestamps in both cases... but finally you've tried to round the number with floor... and of course this will result in 0, if it's less than a year.
test it without rounding first, and test your timestamps, maybe something is wrong there, too?
Im using Github's api to get my latest commits, and the date format returned looks like this
2012-01-25T11:23:28-08:00
I tried to do it like this:
$date = explode('T', $next['commit']['author']['date']);
$time = strtotime($date[0] .' '. $date[1]);
$date = date('M j, Y g:i a', $time);
But it didnt turn out right as php thought I was subtracting 8 hours from the time (because of the timezone). I would like to keep the timezone but i have no clue how to parse that. Does anyone know how to have it where the time is correct and shows the time zone abbreviation (GMT, PST etc etc )?
It cannot get any simpler than this:
$a = new DateTime("2012-01-25T11:23:28-08:00");
echo $a->format("Y-m-d H:i:s");
//outputs 2012-01-25 11:23:28
See the documentation of the DateTime class for more info.
The simple, mechanical, solution is to break the date down yourself completely:
$date = substr($next['commit']['author']['date'], 0, 10);
$time = substr($next['commit']['author']['date'], 11, 9);
$zone = substr($next['commit']['author']['date'], 20, 6);
list($y, $m, $d) = explode('-', $date);
list($h, $i, $s) = explode(':', $time);
$zh = substr($zone, 1, 2);
$zm = substr($zone, 4, 2);
if (substr($zone, 0, 1) == '-'){
$h -= $zh;
$m -= $zm;
}else{
$h += $zh;
$m += $zm;
}
$ts = gmmktime($h,$i,$s,$m,$d,$y);
This will give you a timestamp in UTC.
The issue is with "shows the time zone abbreviation" - you can't find a abbreviation for a given offset, because there can be several - you can't tell which of the e.g. +01:00 timezones the date is in - could be european, african, or bristish summer time.
It really depends what you want to do with the data.