php date string to timestamp - inverse_date() - php

I'm looking for a function that does the inverse of date(). Meaning:
$timestamp = inverse_date($format_string, $date_string);
$d = date($format_string, $timestamp);
if ($d === $date_string) {
echo 'This is what I want';
}
Problems I've run into so far:
strtotime - guesses format, so it might not be good for all formats
strptime - uses strftime's formatting that is different from date's
SOLUTION:
function inverse_date($format_string, $date_string) {
$dateTime = date_create_from_format($format_string, $date_string);
$value_ts = date_format($dateTime, 'U');
return $value_ts;
}
Thanks to Till Helge Helwig for the link.

function inverse_date($format_string, $date_string) {
$dateTime = date_create_from_format($format_string, $date_string);
$value_ts = date_format($dateTime, 'U');
return $value_ts;
}

Related

Convert timestamp with dots in PHP ("yyyy.mm.dd hh:nn:ss.zzz")

I'm trying to convert strings with hungarian datetime format, but no success because of the dot-separators:
<?php
$dtime = DateTime::createFromFormat("YY'.'MM'.'DD HH:MM:II frac", "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Isn't it possible without "string-replace" like this:
strtotime(preg_replace("/([0-9]{4})\.([0-9]{2})\.([0-9]{2})/",'${1}-${2}-${3}',$xml->delivery_time)) ?
(I'm new to PHP 5 and I'm shocked it can not simply convert a common date format. Searched 200+ results, wasted 4+ hours ... no success.)
The correct format is stored in the $format variable:
(Note: the v (millisec) modifier has only been added since v7.3)
<?php
$format = 'Y.m.d H:i:s.v';
$dtime = DateTime::createFromFormat($format, "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Result: 1595457696
This solution will also work for PHP versions below 7.3
// convert a hungarian datetime to a timestamp
function toTimestamp($dt)
{
$format = 'Y.m.d H:i:s.';
if (version_compare(PHP_VERSION, '7.3.0', '<')) {
$dt = explode('.', $dt);
$dt[3] = intval($dt[3] * 1000);
$dt = implode('.', $dt);
$format .= 'u';
} else {
$format .= 'v';
}
return DateTime::createFromFormat($format, $dt)->getTimestamp();
}
$timestamp = toTimestamp('2020.07.22 22:41:36.258');
var_dump($timestamp);

Avoid loop for Date add by day?

I am using Carbon to add number of days, it there a way to avoid using for and/or while loop?
Add the numbers of days ($skipDayBy) and add the number of days if found in $excludeDatesPublic or $excludeDatesManual?
For example working demo:
function calculateDate($skipDayBy = 0) {
$excludeDatesPublic = ['2019-08-28'];
$excludeDatesManual = ['2019-09-01'];
$date = Carbon::now();
for($i = 0; $i < $skipDayBy; $i++) {
$date = $date->addDays(1);
while(in_array($date->toDateString(), $excludeDatesPublic) || in_array($date->toDateString(), $excludeDatesManual))
{
$date = $date->addDays(1);
}
}
return $date->toDateString();
}
echo calculateDate(4);
Returned 2019-09-02 as expected if today date is 2019-08-27.
Maybe you're looking for https://github.com/kylekatarnls/business-day that allows you to add days skipping holidays.
Alternatively, you can use the periods:
$skipDayBy = 5;
$excludeDatesPublic = ['2019-09-01'];
$excludeDatesManual = ['2019-09-04'];
$exclude = array_merge($excludeDatesPublic, $excludeDatesManual);
$date = CarbonPeriod::create(Carbon::now(), $skipDayBy)
->addFilter(function (Carbon $date) use ($exclude) {
return !in_array($date->format('Y-m-d'), $exclude);
})
->calculateEnd();
var_dump($date); // 2019-09-06 18:50:17 if run at 2019-08-31 18:50:17
With PHP shortly
$day='2019-12-12';
$date = date('Y-m-d', strtotime($day . " +4 days"));
echo $date;
Output
2019-12-16
Or u can use
$date= date('Y-m-d', strtotime('+4 days', strtotime($day)));

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

PHP Datetime Convert slash to minus

I want to convert my datetime 08/11/2013 to 2013-08-11.
I was trying this, but it did not work as it suppose to.
$date = $_POST['gt_date']; // Getting 08/11/2013
$date = explode("/", $date); // Exploding the / character into array
$datetime = $date[2] + '-' + $date[0] + '-' + $date[1];
Any Ideas?
You can pass it to DateTime to format it for you.
$date = new DateTime('08/11/2013');
echo $date->format('Y-m-d');
I don't know what the + does, but changing your code to the following will work:
$datetime = $date[2].'-'.$date[0].'-'.$date[1];
Edit: I guess the + was adding them together. Was the result you were getting 2032?
Here's a function that will return your format so that you don't have to repeat your code.
function makeDateFormat($date) {
$date = $_POST['gt_date'];
$date = explode("/",$date);
$new_date = array($date[2], $date[0], $date[1]);
$date = implode("-",$new_date);
return $date;
}
This issue is caused by the "+" operator, replace it with "." operator. You could use this function:
function formatDate($date) {
$arr = explode("-",$date);
$year = $arr[2];
$month = $arr[1];
$day = $arr[0];
return $year."-".$month."-".$day;
}
Nice function but correction is this below if you want to covert format as well:
echo makeDateFormat('13/02/23','Y-m-d');
function makeDateFormat($date,$date_format) {
$date = explode("/",$date);
$new_date = array($date[2], $date[1], $date[0]);
$date = implode("-",$new_date);
$date=date($date_format,strtotime($date));
return $date;
}
Another way if your require to format date as per your requirement:
$date=explode("/","13/02/23");
$new_date_format=date('Y-m-d',strtotime($date[2].'-'.$date[1].'-'.$date[0]));

Calculate years from date

I'm looking for a function that calculates years from a date in format: 0000-00-00.
Found this function, but it wont work.
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
outputs nothing :/
i have error reporting on but i dont get any errors
Your code doesn't work because the function is not returning anything to print.
As far as algorithms go, how about this:
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
This is the same algorithm (just in PHP) as the accepted answer in this question.
A shorter way of doing it:
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
An alternative way to do this is with PHP's DateTime class which is new as of PHP 5.2:
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
See it in action
A single line function can work here
function calculateAge($dob) {
return floor((time() - strtotime($dob)) / 31556926);
}
To calculate Age
$age = calculateAge('1990-07-10');
You need to return $yearDiff, I think.

Categories