This might be a simple, I've $month and $year, but I'm trying to get lastMonthYear and lastToLastMonthYear.
$date = Carbon::create($year, $month)->startOfMonth();
$sameMonthLastYear = $date->subYear()->format('Ym');
$lastMonthYear = $date->subMonth()->format('Ym');
$LastToLastMonthYear = $date->subMonth()->format('Ym');
Considering $month=9 and $year=2021, I'm trying to get
sameMonthLastYear = 202009
lastMonthYear = 202108
lastToLastMonthYear = 202107
but I'm getting
sameMonthLastYear = 202009
lastMonthYear = 202008
lastToLastMonthYear = 202008
Because $date value is keep updating for every line. Is there any way to get the expected result?
The right way is to use CarbonImmutable:
$date = CarbonImmutable::create($year, $month);
$sameMonthLastYear = $date->subYear()->format('Ym'); //202009
$lastMonthYear = $date->subMonth()->format('Ym'); //202108
$LastToLastMonthYear = $date->subMonths(2)->format('Ym'); //202107
With CarbonImmutable, the changes you make to $date are not persisted.
I also removed the startOfMonth method, it was useless since by default, the Carbon instance will be:
Carbon\CarbonImmutable #1630454400 {#5430
date: 2021-09-01 00:00:00.0 UTC (+00:00),
}
You can use copy() method:
$date = Carbon::create($year, $month)->startOfMonth();
$sameMonthLastYear = $date->copy()->subYear()->format('Ym');
$lastMonthYear = $date->copy()->subMonth()->format('Ym');
$LastToLastMonthYear = $date->copy()->subMonths(2)->format('Ym');
Related
my problem is to get date from array. but there is a time from it.
i get data from model
$data['result'] = $this->MTransaksi->cekpengembalian($id_transaksi);
and i want to get datetime
$date4 = $data['result']->tanggal_kembali;
after get the datetime i should split it with explode in php function
$splitTimeStamp = explode(" ",$date4);
and just get the date from it
$date = date('Y-m-d',strtotime($splitTimeStamp));
but the result in view looks like this
enter image description here
so this is full code i wrote
$data['result'] = $this->MTransaksi->cekpengembalian($id_transaksi);
$date4 = $data['result']->tanggal_kembali;
$splitTimeStamp = explode(" ",$date4);
$date = date('Y-m-d',strtotime($splitTimeStamp));
just want to split date and time
You need to update the code as the explode() return an array.
Below I have assigned the array parameters to separate variables and you can use them individually.
$data['result'] = $this->MTransaksi->cekpengembalian($id_transaksi);
$date4 = $data['result']->tanggal_kembali;
$splitTimeStamp = explode(" ",$date4);
$dateObject = $splitTimeStamp[0];
$timeObject = $splitTimeStamp[1];
$date = date('Y-m-d',strtotime($dateObject));
NOTE: You didn't mention your $date4 how it looks otherwise could have provided a more concrete answer.
Hope it helps
I have read the manual - but can't seem to find what I need. I don't need the actual date - I need the date I tell it is from the URL
This is what I have currently:
//create search string for posts date check
if($Day <= 9) {//ensure day is dual digit
$fix = 0;
$Day = $fix . $Day;
}
$Day = preg_replace("/00/", "/0/", $Day);
$date = $_GET["Year"];
$date .= "-";
$date .= $_GET["Month"];
$date .= "-";
$date .= $_GET["Day"];
$currently = mktime (0,0,0,$Month,$Day,$Year,0); //create a timestamp from date components in url feed
//create display date from timestamp
$dispdate = date("l, j F Y",$currently);
When I echo $date it reads correctly for the variable string supplied in the URL but $dispdate always returns the current day that it actually is today. I need $currently to be the timestamp of the date in the URL too.
You seem to construct a valid, readable datestring from the GET parameters. Use
$currently = strtotime($date).
It will return a timestamp that you can use to create the $dispdate like you already do with the date function.
Seems like not all the OP's code was posted, so this is based on what is known.
In the line:
mktime (0,0,0,$Month,$Day,$Year,0)
You are using variables that aren't shown to us (so we must assume are not being set to anything). Above this line you are building a "$date" variable with the URL parameters. This is what should be used in your mktime function.
You could use a Datetime object, pass the given parameters and format the output anyway you want.
<?php
//replace with GET params
$year = 2015;
$month = 10;
$day = 01;
$datetime = new Datetime($year.'-'.$month.'-'.$day);
echo $datetime->format('Y-m-d');
?>
I have created different vars using date_format from one datetime object $date_obj.
$date_obj = date_create($date);
$year = date_format($date_obj, 'Y');
$month = date_format($date_obj, 'm');
$day = date_format($date_obj, 'd');
However I have read (lost source) that this is bad practice? Instead I should create a new datetime object each time because the original object isn't referenced, but directly manipulated.
$date_obj_1 = date_create($date);
$year = date_format($date_obj_1, 'Y');
$date_obj_2 = date_create($date);
$month = date_format($date_obj_2, 'm');
$date_obj_3 = date_create($date);
$day = date_format($date_obj_3, 'd');
Is this true?
The DateTime object is an object, and therefore is passed by reference.
In your example above this won't matter, because you only format a date, you do not manipulate it. However, if you use a DateTime object as an argument in a function and inside this function you manipulate the object, your changes will be visible outside of that function:
function addDays($date,$days){
$date->add(new DateInterval($days.' days'));
}
$date_obj_1 = date_create($date);
$formatedDate1 = date_format($date_obj_1, 'Y-m-d');
addDays($date_obj_1,10);
$formatedDate2 = date_format($date_obj_1, 'Y-m-d');
In the above example $formatedDate1 is different from $formatedDate1 because $date_obj_1 was passed by reference
EDIT: for a detailed explanation on my above snipped look at the comments section. #Xatoo explained it pretty good.
date_format isn't manipulating the DateTime object. What you do is the equivalent of:
$dateObject = new DateTime($date);
$year = $dateObject->format('Y');
$month = $dateObject->format('m');
$day = $dateObject->format('d');
This is absolutely fine, dateObject is not changed by calling the format method on it.
I'm getting in trouble where I was coding for connection using OpenX API with XML-RPC2. I get the problem that the data type is required by the fire function is the dateTime.iso8601.
This is my code:
$sdatetime = new DateTime('2013-01-01 00:00:00');
$edatetime = new DateTime('2013-06-01 00:00:00');
$startDate = $sdatetime->format(DateTime::ISO8601);
$endDate = $edatetime->format(DateTime::ISO8601);
try {
$result = $aClient->agencyPublisherStatistics($sessionId, 1, $startDate, $endDate);
print_r($result);
} catch (XML_RPC2_FaultException $e) {
die('Exception #' . $e->getFaultCode() . ' : ' . $e->getFaultString());
}
This is result error, when I run script above:
Exception #3 : Incorrect
parameters passed to method: Wanted dateTime.iso8601, got string at
param 3
If I run print_r(gettype($startDate)); I get the type data is string not date.
My question, for variables $startDate and $endDate how to make their data type to be dateTime.iso8601 or date rather than string.
Thanks.
it looks like your agencyPublisherStatistics requires specific XML_RPC2_Value date object. You cancreate this by using.
$startDate = XML_RPC2_Value::createFromNative($startDate, ‘datetime’);
same for the end date.. let me know if this works..
Try this,
$sdatetime = date(DATE_ISO8601, strtotime('2013-01-01 00:00:00'));
$edatetime = date(DATE_ISO8601, strtotime('2013-06-01 00:00:00'));
OR
Check below links,
http://pear.php.net/manual/en/package.webservices.xml-rpc2.client.php
https://bugs.php.net/bug.php?id=51950
may this help you.
use DateTime::setISODate
$sdatetime = new DateTime('2013-01-01 00:00:00');
$edatetime = new DateTime('2013-06-01 00:00:00');
$startDate = $sdatetime->setISODate(2013);
$endDate = $edatetime->setISODate(2013);
How can I convert this string 05/Feb/2010:14:00:01 to unixtime ?
Use the strtotime function:
Example:
$date = "25 december 2009";
$my_date = date('m/d/y', strtotime($date));
echo $my_date;
For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.
$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
Versions prior, this should work.
$date = '05/Feb/2010:14:00:01';
$format = '#^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$#';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
date('I')
);
You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.
$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];
Or substr, or explode, whatever you wish to parse that string.
You should look into the strtotime() function.
http://www.php.net/date_parse_from_format
$d="05/Feb/2010:14:00:01";
$dr= date_create_from_format('d/M/Y:H:i:s', $d);
echo $dr->format('Y-m-d H:i:s');
here you get date string, give format specifier in ->format() according to format needed
Simple exploding should do the trick:
$monthNamesToInt = array('Jan'=>1,'Feb'=>2, 'Mar'=>3 /*, [...]*/ );
$datetime = '05/Feb/2010:14:00:01';
list($date,$hour,$minute,$second) = explode(':',$datetime);
list($day,$month,$year) = explode('/',$date);
$unixtime = mktime((int)$hour, (int)$minute, (int)$second, $monthNamesToInt[$month], (int)$day, (int)$year);
If you're up for it, use the DateTime class
Try this:
$new_date=date('d-m-Y', strtotime($date));
If it's a string that you trust meaning that you have checked it before hand then the following would also work.
$date = new DateTime('2015-03-27');