I need to get the end date of the given month for some calculation purpose,
how can I do that in PHP, I tried using date() function, but It didn't work.
I used this:
date($year.'-'.$month.'-t');
But this gives the current month's end date.
I think I'm wrong somewhere, I couldn't find where I'm going wrong here.
If I give year as 2012 & month as 03, then it must show me as 2012-03-31.
This code will give you last day for a specific month.
$datetocheck = "2012-03-01";
$lastday = date('t',strtotime($datetocheck));
You want to replace your date() call with:
date('Y-m-t', strtotime($year.'-'.$month.'-01'));
The first parameter to date() is the format you want to be returned, and the second parameter has to be a unix timestamp (or not passed to use the current timestamp). In your case, you can generate a timestamp with the function strtotime(), passing it a date string with the year, the month, and 01 for the day. It will return that same year and month, but the -t in the format will be replaced by the last day of the month.
If you want to return only the last day of the month without year and month:
date('t', strtotime($year.'-'.$month.'-01'));
Just use 't' as your format string.
Current month:
echo date('Y-m-t');
Any month:
echo date('Y-m-t', strtotime("$year-$month-1"));
Try below code.
$m = '03';//
$y = '2012'; //
$first_date = date('Y-m-d',mktime(0, 0, 0, $m , 1, $y));
$last_day = date('t',strtotime($first_date));
$last_date = date('Y-m-d',mktime(0, 0, 0, $m ,$last_day, $y));
function lastday($month = '', $year = '') {
if (empty($month)) {
$month = date('m');
}
if (empty($year)) {
$year = date('Y');
}
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
function firstOfMonth() {
return date("Y-m-d", strtotime(date('m').'/01/'.date('Y').' 00:00:00')). 'T00:00:00';}
function lastOfMonth() {
return date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')))). 'T23:59:59';}
$date1 = firstOfMonth();
$date2 = lastOfMonth();
try this ,this give you a current month's starting and ending date.
date("Y-m-d",strtotime("-1 day" ,strtotime("+1 month",strtotime(date("m")."-01-".date("Y")))));
function getEndDate($year, $month)
{
$day = array(1=>31,2=>28,3=>31,4=>30,5=>31,6=>30,7=>31,8=>31,9=>30,10=>31,11=>30,12=>31);
if($year%100 == 0)
{
if($year%400 == 0)
$day[$month] = 29;
}
else if($year%4 == 0)
$day[$month] = 29;
return "{$year}-{$month}-{$day[$month]}";
}
If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$a_date = "2012-03-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
Related
I need to find the date of the third saturday of the month.
I've got the following function, which finds me the last saturday of the month
function Get-3rdSaturdayOfMonth {
$Date = Get-Date
$lastDay = new-object DateTime($Date.Year, $Date.Month, [DateTime]::DaysInMonth($Date.Year, $Date.Month))
$diff = ([int] [DayOfWeek]::Saturday) - ([int] $lastDay.DayOfWeek)
if ($diff -ge 0) {
return $lastDay.AddDays(- (7-$diff))
}
else {
return $lastDay.AddDays($diff)
}
}
However, I don't know how to edit it to find the third saturday of the month.
Right now the function goes from last date of the month to the saturday that comes before it. But if I want the third saturday i think i need to calculate from the first day of the month, not the last.
Based on the solution from Brandon, since the third Saturday can't possibly occur before the 15th of the month, we can increment from the 15. until we find a saturday:
$thirdSaturday = [DateTime]::new((Get-Date).Year,(Get-Date).Month,15)
while ($thirdSaturday.DayOfWeek -ne [DayOfWeek]::Saturday)
{
$thirdSaturday = $thirdSaturday.AddDays(1)
}
I'm currently working with jquery FullCalendar plugin to create a specific calendar.
One of my tasks I have to work out is how to get any given specific day for the month.
I'm currently using Coldfusion 10 for the server side so I'm wondering is there any specific way of getting every instance of a Tuesday into an array of dates?
Ideally I would like to do this on the server side and populate the calendar plugin.
My issue is primarily trying to source every specific day of a calendar month.
Any advice greatly appreciated.
The firstXDayOfMonth() UDF on CFLlib allows you to find the first of a given day-of-week in a given month. From there you just need to loop from that date adding 7 each iteration until the month is no long the selected month.
theMonth = month(now());
startDate = firstXDayOfMonth(3, theMonth, year(now()));
tuesdays = [];
for (date=startDate; month(date) == theMonth; date +=7){
arrayAppend(tuesdays, dateAdd("s",0, date)); // this just converts date from a number back to a date
}
writeDump(tuesdays);
Update:
Actually the approach for that UDF on CFLib is terrible. Use this variation instead:
function firstXDayOfMonth(dayOfWeek,month,year){
var firstOfMonth = createDate(year, month,1);
var dowOfFirst = dayOfWeek(firstOfMonth);
var daysToAdd = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
var dow = dateAdd("d", daysToAdd, firstOfMonth);
return dow;
}
I'll update the UDF on cflib a bit later: I need to write some decent unit tests for it first, and am a bit busy # the moment.
The Short Version:
At this time, there is not a function in CF that gets all the Tuesdays. But here's an easy way to do it:
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1
var dayOfWeekArray = []; // This is the outcome.
// loop through each day of the month adding the target days to the array.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, loopingDate );
}
}
dayOfWeekArray is an array of every Tuesday of a month.
More Detail:
Your title and post seem to conflict as far as what you're looking for, so I'm going to stick with the title, since that's why I came here...
Here's what you can do to find all the Tuesdays in a month:
Create a date Object
Loop through the days in the target month using the date Object
If the current day is Tuesday, add it to an array
Boom, you got all the Tuesdays of a month in an array
Here's the code I used (cfscript):
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var dayOfWeekArray = [];
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1. Do a quick writeDump in the loop if you're not sure.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, datePart( "d", loopingDate );
// ArrayAppend( dayOfWeekArray, loopingDate ); - use this if you'd rather have the whole date object
}
}
This gives you dayOfWeekArray which will be the date of each Tuesday of a particular month. For instance, this month (Jan 2019) will be [1, 8, 15, 22, 29]. You can change this to be the entire date object if you want - that's what I did in the short version at the top.
I computed the difference of two ISO 8601 dates after coverting them to epoch.
How can I get the difference of them in number of days?
My code is
my $ResolvedDate = "2014-06-04T10:48:07.124Z";
my $currentDate = "2014-06-04T06:03:36-04:00"
my $resolved_epoch = &convert_time_epoch($ResolvedDate);
my $current_epoch = &convert_time_epoch($currentDate);
if (($resolvedDate - $currentDate) > $noOfDays) {
print "Difference in greater than x\n";
$built = 0;
return ($built);
} else {
print "Difference in smaller than x \n";
$built = 1;
return ($built);
}
sub convert_time_epoch {
my $time_c = str2time(#_);
my #time_l = localtime($time_c);
my $epoch = strftime("%s", #time_l);
return($epoch);
}
Here in addition to $built I also want to return exact number of days, Resolved date is greater than Current date.
"number of days" is awkward, because this is localtime and DST exists (or at least, may exist).
By simply dividing by 86400 you can easily obtain the number of 24-hour periods, which may be sufficient for your purposes.
If you want the true number of times that the mday field has changed, this may be slightly different from the value obtained by this simple division, however.
If the dates are in epoch seconds, take the difference and divide it by the number of seconds in a day (which is 86400). Like so:
my $days_difference = int(($time1 - $time2) / 86400);
If you use DateTime then
my $duration = $dt1->delta_days($dt2); #$dt1 and $dt2 are DateTime objects.
print $duration->days;
use DateTime::Format::ISO8601 qw( );
my $ResolvedDate = "2014-06-04T10:48:07.124Z";
my $currentDate = "2014-06-04T06:03:36-04:00";
my $format = DateTime::Format::ISO8601->new();
my $dt_resolved = $format->parse_datetime($ResolvedDate);
my $dt_current = $format->parse_datetime($currentDate);
my $dur = $dt_resolved->delta_days($dt_current);
my $days = $dur->in_units('days');
I try to generate a list of days with their week number (defined by ISO 8601) accordingly :
mydate='2012-12-25 02:26:55.983'
for (i=1;i<365;i++)
{
mydateAsDate=new Date().parse('yyyy-MM-dd H:mm:ss.S',mydate)+i;
println 'Week ' + mydateAsDate.format('w') + ' => ' + mydateAsDate.format('dd.MM.yyyy');
}
This works but I would like to get the year also like this:
Week 1-2013
I can't figure out which year information I should take.
Any idea?
As Jon Skeet said, I'd recommend using Joda-Time.
If you do, the following should fix your issues:
mydate= new DateTime(2012,12,25)
yearLater = myDate.plusYears(1)
while(myDate < yearLater){
println "Week ${myDate.weekOfWeekyear} - ${myDate.year}"
myDate = myDate.plusDays(1)
}
Not sure I understand, but you mean like:
String startDateString = '2012-12-25 02:26:55.983'
Date startDate = Date.parse( 'yyyy-MM-dd H:mm:ss.S', startDateString )
(1..364).each { i ->
println( (startDate++).format( "dd.MM.yyyy : 'Week' w'-'yyyy" ) )
}
I got it : SimpleDateFormat delivers the right week year information when using the YYYY format
thus this is only available in java 1.7
thanks for your responses though !
cheers
I have been using the following code for the last few months, which loops through a period of months from a predefined date until it gets to today's date.
use Date::Pcalc qw(:all);
$startDay = 1;
$startMonth = '4';
$startYear = '2009';
$dateToday = `date +%Y-%m-%d`;
($yt,$mt,$dt) = split(/\-/,$dateToday);
while ($endMonth <= $mt || $startYear < $yt ) {
if ($startMonth eq '12') {
$endMonth = 1;
$endYear = $startYear + 1;
} else {
$endMonth = $startMonth + 1;
$endYear = $startYear;
}
if ($startMonth eq '12') {
$endYear = $startYear + 1;
}
($meYear,$meMonth,$meDay) = Add_Delta_Days($endYear,$endMonth,$startDay,-1);
$endOfMonth = "$meYear-$meMonth-$meDay";
$monthText = Month_to_Text($startMonth);
$startDate = "$startYear-$startMonth-1";
$endDate = "$endYear-$endMonth-1";
print "$startDate - $endDate\n";
if ($startMonth eq '12') {
$startMonth = 1;
$startYear++;
} else {
$startMonth++
}
}
This has been working great for the last few months, but I've realised that now in December, as $endmonth will never be greater $mt (12), this causes an infinite loop.
I've not been able to figure out any alternate way of doing this. I feel like I should be able to fix this relatively easily but I seem to be having severe 'developer's block'
Thanks in advance to anyone who can assist.
my $date = DateTime->new(
time_zone => 'local',
year => $startYear,
month => $startMonth,
day => 1,
);
my $today = DateTime->today(time_zone => 'local');
while ($date <= $today) {
say $date->ymd('-');
$date->add( months => 1 );
}
I think you have a couple of problems with your code. But lets get to the first problem which is the enddate in month 12 which causes a loop in this statement:
while ($endMonth <= $mt || $startYear < $yt ) {
OK what you should do is something like this, once you have the current date, year month and day. You will notice that others have suggested different way to get the current date You should take up this suggestion. However once you have the date this code below should be adopted:
($yt,$mt,$dt) = split(/\-/,$dateToday);
# the line below will create a date like 201212 (yyyy mm) but if the month is a 1 digit month it will place a 0 in front of it to ensure your yymm variable always holds 6 characters in the format of yyyy mm - ok
my $yymm = $yt . ${\(length($mt) == 1 ? '0' : '')} . $mt;
# Now lets check the end date against the yymm
# initialise end date as end_yymm - again it inserts a 0 for single digit month
my $end_yymm = $startyear . ${\(length($startMonth) == 1 ? '0' : '')} . $startMonth;
# the above should get the date as '200904' from your code provide
# the while will check end_yymm like 200904 < 201212 - yes it is...
## the end_yymm will keep getting incremented each month and so will the year component at the end of each year until it reaches 201212
## then the question 201212 < 201212 will cause the while to end
## If you want it go into 201301 then say while ($end_yymm <= $yymm) {
## Hope you get the picture
while ($end_yymm < $yymm) {
if ($startMonth eq '12') {
$endMonth = 1;
$endYear = $startYear + 1;
} else {
$endMonth = $startMonth + 1;
$endYear = $startYear;
}
## Now this one seems to be repeating the endYear calculation as above - to me it seems redundant - maybe get rid of it
if ($startMonth eq '12') {
$endYear = $startYear + 1;
}
## Now that you have the end year and month incremented setup the end_yymm variable again to be picked up in the while statement:
$end_yymm = $startyear . ${\(length($startMonth) == 1 ? '0' : '')} . $startMonth;
# ...... carry on with the rest of your code
} # end the while loop
And that should do it.
All the best