Remove day from date format in php - php

Can someone help me please, I need a function or a way in PHP, to exclude the day from a given date regardless of its format.
Thank you.

try this
$newdate = date("m-Y",strtotime($date));

I ran into this as well, and made preg match to check for 2 date formats with year notation yyyy. Not the solution I'd prefer, but it works for me. Downside is that you have to define all the date formats and it depends on yyyy notation.
// check form to be yyyy-mm-dd
if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D', $date)){
$date = date("Y-m", $date);
}
// check form to be mm-dd-yyyy
elseif (preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/D', $date)){
$date = date("m-Y", $date);
}

I am answering this for people who have encountered the same problem
if (!function_exists('remove_days_in_date')) {
/**
* This function allows you to delete some number of days in a date
* #param \DateTime $date The date in which to delete the days
* #param int $n_day The number of days to delete
* #return string
*/
function remove_days_in_date(\DateTime $date, int $n_day) {
date_sub($date,date_interval_create_from_date_string("$n_day days"));
date_format($date,"Y-m-d h:i:s");
return date_format($date,"Y-m-d h:i:s");
}
}
echo remove_days_in_date(new \DateTime, 12);

Related

Retrieve items by month and year with Symfony and Doctrine

I need to retrieve all items of a particular type with Doctrine, where the 'date' field is stored as DateTime. Which means I'm working with the PHP DateTime object as well.
I need to do two things overall: if given a month and year, retrieve all records for that month and year; and if not given a month and year, retrieve all records for this month.
I've been looking at using BETWEEN statements in the Doctrine Query Builder, but can't figure out how to cleanly extract the month and year from PHP DateTime objects created 'now' so that the time portion of DateTime doesn't affect the query. I also can't see a way of just setting the day portion of the Date in DateTime to be 01 either, without affecting the month and year.
I thought this would be a fairly standard task but can't find a solution. Any help appreciated.
EDIT:
Found a hacky way to get the dates for between, but Doctrine is returning an empty array. Using the following code
/**
* Returns feed for month and year
*/
public function getMonthYearFeed($month, $year)
{
// Create two times at the start of this month and next month
$startDate = \DateTime::createFromFormat('d-n-Y', "01-".$month."-".$year);
$startDate->setTime(0, 0 ,0);
$endDate = \DateTime::createFromFormat('d-n-Y', "01-".($month+1)."-".$year);
$endDate->setTime(0, 0, 0);
$notes = $this->em->getRepository('AppBundle:Note')->createQueryBuilder('n')->where('n BETWEEN :start AND :end')->setParameter('start', $startDate->format('Y-m-d H:i:s'))->setParameter('end', $endDate->format('Y-m-d H:i:s'))->getQuery()->getResult();
return $notes;
}
Putting something like this in your Repository should get you started. I haven't tested it aside from the 'last day of this month' bit which seems to work fine.
/**
* #param int $month
* #param int $year
*
* #return object[]
*/
public function findByDate($year = null, $month = null)
{
if ($month === null) {
$month = (int) date('m');
}
if ($year === null) {
$year = (int) date('Y');
}
$startDate = new \DateTimeImmutable("$year-$month-01T00:00:00");
$endDate = $startDate->modify('last day of this month')->setTime(23, 59, 59);
$qb = $this->createQueryBuilder('object');
$qb->where('object.date BETWEEN :start AND :end');
$qb->setParameter('start', $startDate->format('‌​Y-m-d H:i:s'));
$qb->setParameter('end', $endDate->format('‌​Y-m-d H:i:s'));
return $qb->getQuery()->getResult();
}
Very importand moment. Use data type of setParameter.
Like this for symfony.
use Doctrine\DBAL\Types\Type;
$query->setParameter('start', $startDate, Type::DATETIME);
This appears to be working, although I will definitely need to modify the way I construct the dates (and move the function into the repo). I had originally forgotten the '.date' bit of DQL, and there was no need to output the DateTime object as a format.
// Create two times at the start of this month and next month
$startDate = \DateTime::createFromFormat('d-n-Y', "01-".$month."-".$year);
$startDate->setTime(0, 0 ,0);
$endDate = \DateTime::createFromFormat('d-n-Y', "01-".($month+1)."-".$year);
$endDate->setTime(0, 0, 0);
$notes = $this->em->getRepository('AppBundle:Note')->createQueryBuilder('n')->where('n.date BETWEEN :start AND :end')->setParameter('start', $startDate)->setParameter('end', $endDate)->getQuery()->getResult();
// $notes = $this->em->getRepository('MrshllSiteBundle:Note')->findByDate();
return $notes;

How can I change more than a date format in a unique format with a single php function?

I would like to understand how to change different date formats into a single format using a php function. After trying in every way, i wasn't able to solve this puzzle. I always just used the following code in my custom function.php smoothly:
/* Change date format for coupon */
function change_date_format($x) {
$date = DateTime::createFromFormat('j-M-Y', $x);
$x = $date->format('Y-m-d');
return $x;
}
In this way i can convert the format 'j-M-Y' in the format 'Y-m-d'. The problem is that now i need to convert not only the date format 'j-M-Y', but also other formats (for example, i've to convert date format 'j-M-Y' and date format 'Y-m-d\TH:i:sP' in date format 'Y-m-d'. I tried to combine different logic functions but system gives me error.
Thanks to all of you who try to help me...
The DateTime class is pretty good at parsing different formats without createFromFormat(). If the formats you have are supported (Supported Date and Time Formats) then just let it create based on the in-built logic. If $x = '2016-06-30T23:59:59+02:00' then the DateTime class handles this just fine:
function change_date_format($x) {
$date = new DateTime($x);
return $date->format('Y-m-d');
}
Add an input parameter to your function called: $inputFormat and use this instead 'j-M-Y', so you should specify always the input format. You can specify a default format for input.
/**
* Return with a normal format of any date by given format
* Default format is j-M-Y if no input format given
*
* #param string $dateString
* #param string $inputFormat
* #return string
*/
function change_date_format($dateString, $inputFormat = 'j-M-Y') {
$date = DateTime::createFromFormat($inputFormat, $dateString);
return $date->format('Y-m-d');
}
echo change_date_format('23-05-2016', 'd-m-Y');
echo change_date_format('05/23/2016', 'm/d/Y');
You can use an additional parameter as follows:
/*Change date format for coupon*/
function change_date_format($x, $dateFormat) {
$date = DateTime::createFromFormat($dateFormat, $x);
$x = $date->format('Y-m-d');
return $x;
}

PHP Time Difference - diff [duplicate]

This question already has answers here:
How to calculate the difference of datetime field and now in PHP?
(3 answers)
Closed 9 years ago.
I have utilised some code already found on another question.
<?
$start_date = new DateTime('now');
$timestamp = strtotime( $nt['last_seen'] );
$since_start = $start_date->diff($timestamp);
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
?>
This does not seem to work ?? the timestamp is pulled in from mysql statement in the format.
yyyy-mm-dd hh:mm:ss
The first parameter in diff() method expects a DateTime object, but you're supplying a Unix timestamp instead.
Use the following code instead:
$start_date = new DateTime('now');
$end_date = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($end_date);
echo $since_start->format('%i').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
Demo!
As Glavić notes in the comment below, it's possible to create a DateTime object from a Unix timestamp, too:
$date = new DateTime("#$timestamp"); // $timestamp is astring -- eg: 1382025097
But it is not necessary in this case, and the first method should work just fine.
$start_date = new DateTime('now');
$timestamp = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($timestamp);
echo $since_start->format('%m').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
you need to cast your $timestamp as a new DateTime something like the above
I have a couple of wrapper functions I use look at the db date diff one sql query if you're pulling your $timestamp from the database then there's no reason you can't do the diff in your master query and completely remove the need to do it in PHP after.
/**
* Date Diff between now and submitted data
* #param - $date - takes current date
* #return int number of days between inputted dates +ve numbers are start date in past -ve numbers are end date in future of now()
*/
function daves_date_diff($date) {
$start = new DateTime($date);
$today = new DateTime();
$diff = $start->diff($today);
return $diff->format('%d');
}
/**
* Database select based date diff as its more reliable than using php date diffs
* #param - $date - date string in mysql format of date to diff against
* #return - int - number of days date is different from now
*/
function db_date_diff($date) {
global $db;
$date = mysqli_real_escape_string($db->mysqli,$date);
$returneddiff = $db->queryUniqueObject("SELECT DATEDIFF('$date',NOW()) as DateDiff",ENABLE_DEBUG);
return $returneddiff->DateDiff;
}

Adjust a PHP date to the current year

I have a PHP date in a database, for example 8th August 2011. I have this date in a strtotime() format so I can display it as I please.
I need to adjust this date to make it 8th August 2013 (current year). What is the best way of doing this? So far, I've been racking my brains but to no avail.
Some of the answers you have so far have missed the point that you want to update any given date to the current year and have concentrated on turning 2011 into 2013, excluding the accepted answer. However, I feel that examples using the DateTime classes are always of use in these cases.
The accepted answer will result in a Notice:-
Notice: A non well formed numeric value encountered......
if your supplied date is the 29th February on a Leapyear, although it should still give the correct result.
Here is a generic function that will take any valid date and return the same date in the current year:-
/**
* #param String $dateString
* #return DateTime
*/
function updateDate($dateString){
$suppliedDate = new \DateTime($dateString);
$currentYear = (int)(new \DateTime())->format('Y');
return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}
For example:-
var_dump(updateDate('8th August 2011'));
See it working here and see the PHP manual for more information on the DateTime classes.
You don't say how you want to use the updated date, but DateTime is flexible enough to allow you to do with it as you wish. I would draw your attention to the DateTime::format() method as being particularly useful.
strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );
This takes the day and month of the original time, adds the current year, and converts it to the new date.
You can also add the amount of seconds you want to add to the original timestamp. For 2 years this would be 63 113 852 seconds.
You could retrieve the timestamp of the same date two years later with strtotime() first parameter and then convert it in the format you want to display.
<?php
$date = "11/08/2011";
$time = strtotime($date);
$time_future = strtotime("+2 years", $time);
$future = date("d/m/Y", $time_future);
echo "NEW DATE : " . $future;
?>
You can for instance output it like this:
date('2013-m-d', strtotime($myTime))
Just like that... or use
$year = date('Y');
$myMonthDay = date('m-d', strtotime($myTime));
echo $year . '-' . $myMonthDay;
Use the date modify function Like this
$date = new DateTime('2011-08-08');
$date->modify('+2 years');
echo $date->format('Y-m-d') . "\n";
//will give "2013-08-08"

calculating a date and returning the week number depending on the start date in php?

im trying to create a function that takes a $start_date as parameter and it should calculate which week number we are in i.e
for instance $start_date equals 2012-08-16
private function get_week_number($start_date){
// get current date
// caluculate the difference between start_date and current_date
// determine which week we are in 1, 2 or 3
// return $week
}
how can i implement this in php? thanks
function get_week_number($start_date){
$date = date('U', strtotime($start_date));
$now = date('U');
return ceil(($now-$date)/60/60/24/7);
}
echo get_week_number('2012-08-16');
I think what you need is merely date_diff.
private function get_week_number($start_date){
return date('W') - date('W', strtotime($start_date));
}

Categories