I have a table, called schedules. It has three columns day, month, year, the the day/month/year that schedule is for. There is no timestamp here. I chose this format so that I could for instance retrieve all the schedules for October, or for the year 2014.
However, is it possible to retrieve the schedules for given range, say from Sept 10, 2014 to Oct 09, 2014? The problem is that if I use
WHERE 'day' > 10 AND 'day' < 9 ...
will not return anything since even though the month October (10) is larger than September (9), the days of the month will miss this up!
Is there a way or do I need to also include a fourth date column with a timestamp?
You can use parenthesis and an or clause:
WHERE ('month' = '9' AND 'day' > 10) OR ('month' = '10' AND 'day' < 9)
However, using a datetime field would be much better, as you can still get month/day/year easily:
WHERE MONTH(field) = 10
WHERE DAY(field) = 3
WHERE YEAR(field) = 2014
and then you also can do
WHERE field >= '2014-09-10' AND field <= '2014-10-09'
See http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html for documentation on all the date/time functions in mysql.
Related
I have two times saved in database as
DayTime1 = "Wed 09:00"
DayTime2 = "Wed 13:00"
I want to get the difference between these two dates in minutes.
TIMESTAMPDIFF(MINUTES,DayTime1,DayTime2) return null
I'm not able to get through it. Is there any way to get difference?
Please note, that SELECT STR_TO_DATE("Wed 09:00", "%a %H:%i") returns 0000-00-00 09:00:00 (at least on my local MySql 5.5.16). So if comparing different days, you won't get the correct result.
If given a year and week, the day name will be interpreted to a real date, so comparisons may also span days. For example (though not really elegant, I admit):
SELECT TIMESTAMPDIFF(MINUTE,
STR_TO_DATE(CONCAT(YEAR(CURDATE()), WEEKOFYEAR(CURDATE()), ' Tue 09:00'), '%x%v %a %H:%i'),
STR_TO_DATE(CONCAT(YEAR(CURDATE()), WEEKOFYEAR(CURDATE()), ' Wed 13:00'), '%x%v %a %H:%i')
)
Since you also included the php-tag, I'm assuming a PHP solution is valid as well:
$daytime1 = "Wed 09:00";
$daytime2 = "Wed 13:00";
$diff = abs(strtotime($daytime1) - strtotime($daytime2)); //absolute diff in seconds
$diff = $diff / 60; //Difference in minutes
EDIT:
And here is a pure MySQL solution:
SELECT ABS(
TIME_TO_SEC(
TIMEDIFF(
STR_TO_DATE("Wed 09:00", "%a %H:%i"),
STR_TO_DATE("Wed 13:00", "%a %H:%i")
)
)
) / 60
The second parameter, "%a %H:%i"is the date format. If it's always in the format of "First three letters of weekday, space, hour with leading zero, :, minutes" then you can use this format.
I need to calculate number of days between two dates.
Required date entered by me,fetch the record from the database by the given dates.
If the database have 'startdate' as 1Jan2015 'enddate' as 5Feb2015.
For January month it should return 30 and for February 5 days.
My table:
id Name Type Project Place Start Date End Date Details
1 Sai Local Site Bangalore 2015-09-03 11:32:47 2015-09-05 11:32:47 test
2 Ram Local IGCAR Chennai 2015-04-01 15:15:36 2015-04-09 15:15:36 Installation
3 Mani Local IGCAR Chennai 2015-04-16 15:16:18 2015-05-21 15:16:18 Training
My coding
///////////Employee Outstation(Travel) details/////////////
$employeeTravel = new EmployeeTravelRecord();
//date_start = '2015-04-01' ;
//date_end = '2015-04-30';
$TravelEntryList = $employeeTravel->Find("(travel_date between ? and ? or return_date between ? and ? )",array($req['date_start'], $req['date_end'],$req['date_start'], $req['date_end']));
foreach($TravelEntryList as $Travelentry){
$amount = (strtotime($Travelentry->return_date) - strtotime($Travelentry->travel_date));
}
For second record, it returns correct value, but for third record it calculates including May month. But i want only 30 days of april.
DATEDIFF() returns value in days from one date to the other.
select *,datediff( end Date, Start Date) as days from My table;
Please have a look at this post, you should find what you're looking for :
How to get the number of days of difference between two dates on mysql?
There is a function in PHP called as date_diff for difference between two dates.
<?php
$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff = date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
I wan't to get a PHP date() from specified weekday in a given week.
For example:
Weekday: Thursday - in week:8 - year:13 (means 2013).
I would like to return a date from these specified values. The phpdate will in this case return: "21 Feb 2013", which is a Thursday in week 8 of 2013.
Please fill in this php-method:
function getDateWithSpecifiedValues($weekDayStr,$week,$year) {
//return date();
}
Where the example:
getDateWithSpecifiedValues("Tuesday",8,13);
will return a phpdate of "19 Feb 2013"
First, you have to define what you mean by "week of the year". There are several different definitions. Does the first week start on Jan 1? On the first Sunday or Monday? Is it number 1 or 0?
There is a standard definition, codified in ISO 8601, which says that weeks run from Monday through Sunday, the first one of the year is the one with at least 4 days of the new year in it, and that week is number 1. Your example expected output is consistent with that definition.
So you can convert the values by putting them into a string and passing that string to strptime, along with a custom format string telling it what the fields in the string are. For example, the the week number itself should be indicated in the format string by %V.
For the weekday, the format depends on how you want to provide it as input to your function. If you have the full name (e.g. "Thursday"), that's %A. If you have the abbreviated name (e.g. "Thu"), that's %a. If you have a number (e.g. 4), that's either %w (if Sundays are 0) or %u (if Sundays are 7). (If you're not sure, you can always just use %w and pass the number % 7.)
Now, the year should be %G (full year) or %g (just the last two digits). It's different from the normal calendar year fields (%Y for 2014 and %y for 13) because, for example, week 1 of 2014 actually started on December 30, 2013, which obviously has a '%Y' of 2013 where we want 2014. However, the G fields don't work properly with strptime, so you'll have to use the Y's.
For example:
$date_array = strptime("$weekDayStr $week $year", '%A %V %y');
That's a good start, but the return value of strptime is an array:
array('tm_sec' => seconds, 'tm_min' => minutes, tm_hour => hour,
tm_mday => day of month, tm_mon => month number (0..11), tm_year => year - 1900)
And that array is not the input expected by any of the other common date or time functions, as far as I can tell. You have to pull the values out yourself and modify them in some cases and pass the result to something to get what you want. For instance:
$time_t = mktime($date_array['tm_hour'], $date_array['tm_min'],
$date_array['tm_sec'], $date_array['tm_mon']+1,
$date_array['tm_mday'], $date_array['tm_year']+1900);
And then you can return that in whatever form you need. Here I'm returning it as a string:
function getDateWithSpecifiedValues($weekDayStr,$week,$year) {
$date_array = strptime("$weekDayStr $week $year", '%A %V %y');
$time_t = mktime($date_array['tm_hour'], $date_array['tm_min'],
$date_array['tm_sec'], $date_array['tm_mon']+1,
$date_array['tm_mday'], $date_array['tm_year']+1900);
return strftime('%d %b %Y', $time_t);
}
For example,
php > print(getDateWithSpecifiedValues('Thursday',8,13)."\n");
21 Feb 2013
Try this function:
function getDateWithSpecifiedValues($weekDayStr, $week, $year) {
$dt = DateTime::createFromFormat('y, l', "$year, $weekDayStr");
return $dt->setISODate($dt->format('o'), $week, $dt->format('N'))->format('j M Y');
}
demo
I'm fairly certain neither 21st of January or the 19th of January is in week 8.
You can however use strptime to parse custom formats:
var_dump(strptime("Thursday 8 13", "%A %V %y"));
array(9) {
["tm_sec"]=>
int(0)
["tm_min"]=>
int(0)
["tm_hour"]=>
int(0)
["tm_mday"]=>
int(21)
["tm_mon"]=>
int(1)
["tm_year"]=>
int(113)
["tm_wday"]=>
int(4)
["tm_yday"]=>
int(58)
["unparsed"]=>
string(0) ""
}
See the documentation for strptime for the meaning of each value in the returned array.
I'm trying to get an average of a value for the past 2 months, but not based on CURDATE()/NOW(). It would be dependent on what month the user was looking at in the application:
Ex:
If I'm looking at May, I would want the average of April and March.
If I'm looking at February, I would want the average of January and December (of the previous year).
I have a function that accepts the month and year of the page the user is on (it also accepts the emp_id, but that is irrelevant for this question).
public function getProtectedAmt($month,$year,$id){
$query = "SELECT avg(total_payout) as avg_payout FROM saved_plan_data WHERE emp_id = '$id' AND //this is where i dont know what to query for";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
return $row['avg_payout'];
}
In the table saved_plan_data, there are fields plan_month and plan_year that store INT values of what month/year the employee's total_payout is saved for.
How do I write my WHERE clause to get the AVG for the previous 2 months, depending on what the values of $month and $year are?
I think the easier and more readable solution is this one:
SELECT ...
FROM ...
WHERE
(plan_year, plan_month) IN ((2012, 12), (2013, 1))
You just need to compute the appropriate values.
This is also quite readable:
WHERE CONCAT_WS('-', plan_year, plan_month) IN ('2012-12', '2013-01')
In the function, create two variables $q_month & $q_year.
Set these as comma separated past two months. E.g. if currently the date is May 22, 2013, set the values to $q_month = 4,3 and $q_year = 2013
Use these variables in your query as WHERE Month in ($q_month) and Year in ($q_year)
Edit: Mis-read the question. This would get you the average for the last two months combined.
You could either be very verbose saying where (month and year) or (month and year)
SELECT avg(total_payout) as avg_payout
FROM saved_plan_data
WHERE emp_id=$id
AND (
(plan_month = $month1 AND plan_year = $year1)
OR (plan_month = $month2 AND plan_year = $year2)
)
Or you can cast the plan_month and plan_year as a date and check if the value is between two dates:
SELECT avg(total_payout) as avg_payout
FROM saved_plan_data
WHERE emp_id=$id
AND STR_TO_DATE(CONCAT_WS('-',plan_year,plan_month,'1'),'%Y-%m-%d')
BETWEEN '$year1-$month1-1' AND '$year2-$month2-1'
Also, you really should just store the month and year together. Here is a SO question with good answers about it: mysql datatype to store month and year only
I think the easiest way is to think of the year/month combinations as a number of months since year/month 0. That is, convert to number of months by multiplying the year times 12 and adding the months.
Then the previous two months is easy, and you don't have to worry about year boundaries:
SELECT avg(total_payout) as avg_payout
FROM saved_plan_data
WHERE emp_id = '$id' AND
plan_year*12 + plan_month in ($year*12+month - 1, $year*12+month - 2)
I need to create functions in PHP that let me step up/down given datetime units. Specifically, I need to be able to move to the next/previous month from the current one.
I thought I could do this using DateTime::add/sub(P1M). However, when trying to get the previous month, it messes up if the date value = 31- looks like it's actually trying to count back 30 days instead of decrementing the month value!:
$prevMonth = new DateTime('2010-12-31');
Try to decrement the month:
$prevMonth->sub(new DateInterval('P1M')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('-1 month')); // = '2010-12-01'
$prevMonth->sub(DateInterval::createFromDateString('+1 month')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('previous month')); // = '2010-12-01'
This certainly seems like the wrong behavior. Anyone have any insight?
Thanks-
NOTE: PHP version 5.3.3
(Credit actually belongs to Alex for pointing this out in the comments)
The problem is not a PHP one but a GNU one, as outlined here:
Relative items in date strings
The key here is differentiating between the concept of 'this date last month', which, because months are 'fuzzy units' with different numbers of dates, is impossible to define for a date like Dec 31 (because Nov 31 doesn't exist), and the concept of 'last month, irrespective of date'.
If all we're interested in is the previous month, the only way to gaurantee a proper DateInterval calculation is to reset the date value to the 1st, or some other number that every month will have.
What really strikes me is how undocumented this issue is, in PHP and elsewhere- considering how much date-dependent software it's probably affecting.
Here's a safe way to handle it:
/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.
Returns a DateTime object with incremented month/year values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0, $yearIncrement = 0) {
$startingTimeStamp = $startDate->getTimestamp();
// Get the month value of the given date:
$monthString = date('Y-m', $startingTimeStamp);
// Create a date string corresponding to the 1st of the give month,
// making it safe for monthly/yearly calculations:
$safeDateString = "first day of $monthString";
// Increment date by given month/year increments:
$incrementedDateString = "$safeDateString $monthIncrement month $yearIncrement year";
$newTimeStamp = strtotime($incrementedDateString);
$newDate = DateTime::createFromFormat('U', $newTimeStamp);
return $newDate;
}
Easiest way to achieve this in my opinion is using mktime.
Like this:
$date = mktime(0,0,0,date('m')-1,date('d'),date('Y'));
echo date('d-m-Y', $date);
Greetz Michael
p.s mktime documentation can be found here: http://nl2.php.net/mktime
You could go old school on it and just use the date and strtotime functions.
$date = '2010-12-31';
$monthOnly = date('Y-m', strtotime($date));
$previousMonth = date('Y-m-d', strtotime($monthOnly . ' -1 month'));
(This maybe should be a comment but it's to long for one)
Here is how it works on windows 7 Apache 2.2.15 with PHP 5.3.3:
<?php $dt = new DateTime('2010-12-31');
$dt->sub(new DateInterval('P1M'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('-1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->sub(DateInterval::createFromDateString('+1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('previous month'));
print $dt->format('Y-m-d').'<br>'; ?>
2010-12-01
2010-11-01
2010-10-01
2010-09-01
So this does seem to confirm it's related to the GNU above.
Note: IMO the code below works as expected.
$dt->sub(new DateInterval('P1M'));
Current month: 12
Last month: 11
Number of Days in 12th month: 31
Number of Days in 11th month: 30
Dec 31st - 31 days = Nov 31st
Nov 31st = Nov 1 + 31 Days = 1st of Dec (30+1)