I'm trying to group together dates into a week number and year, and then I want to convert that week number back into a unix timestamp. How can I go about doing this?
I assume you are using ISO 8601 week numbers, and want the first day of a ISO 8601 week so that e.g. Week 1 of 2011 returns January 3 2011.
strtotime can do this out of the box using the {YYYY}W{WW} format:
echo date("Y-m-d", strtotime("2011W01")); // 2011-01-03
Note that the week number needs to be two digits.
Shamefully, DateTime::createFromFormat, the fancy new PHP 5 way of dealing with dates, seems unable to parse this kind of information - it doesn't have a "week" placeholder.
$week: The week number
$year: The year number
Then:
$timestamp = gmmktime (0, 0 , 0 , 1, , 4 + 7*($week - 1), $year);
The 4 + 7*($week - 1) comes from the fact that according to ISO 8601, the first week of the year is the one that contains January 4th.
strtotime('1/1/2011 + 4 weeks') (1/1 ist always in week number one; this would bring me to week number five). if you want any timestamp in the week then that's all you need, else you would have to go to the monday in this week:
$t = strtotime('1/1/2011 + 4 weeks');
$t -= 24 * 60 * 60 * date('w', $t);
Update: Instead of 1/1/2011 use the first monday in 2011. The 2nd calculation is not needed anymore.
Related
How do I find out the number of days until the next January 1 without specifying a year?
I always want to know how many days until the next January 1, so I don't want to say "how many until Jan 1, 2020" or I'll need to reset my variable every year.
You can use DateTime objects to do the math. Create one object which is today, and another which is January 1, to which we then add a year, and then take the difference:
$today = new DateTime();
$jan1 = new DateTime('January 1');
$jan1->modify('+1 year');
$days = $today->diff($jan1)->days;
echo "$days days until January 1\n";
Output (on December 6)
25 days until January 1
Demo on 3v4l.org
I want to read dates from an Excel File, but when I print
the dates to the screen I can only see one number instead Of
the date, why?
Excel file:
Result:
Excel treats dates as numbers, with the number representing the number of days after December 31 1899. So day 1 is January 1 1900, and day 43102 is January 3 2018. But wait... your data says January 2 2018! It turns out that Microsoft thinks that 1900 was a leap year and so day 60 is February 29 1900 when in the real world it was actually March 1. Anyway, what that means is that for dates after February 28 1900, you need to subtract one from the day number to get the correct date. So, to convert an Excel day number to a date in PHP, you use the following code:
$dayval = 43102; // you would read from your file here
$date = new DateTime('1899-12-31');
$date->modify("+$dayval day -1 day");
echo $date->format('Y-m-d');
Output:
2018-01-02
Please use this formula to change from Excel date to Unix date, then you can use "gmdate" to get the real date in PHP:
UNIX_DATE = (EXCEL_DATE - 25569) * 86400
and to convert from Unix date to Excel date, use this formula:
EXCEL_DATE = 25569 + (UNIX_DATE / 86400)
After putting this formula into a variable, you can get the real date in PHP using this example:
$UNIX_DATE = ($EXCEL_DATE - 25569) * 86400;
echo gmdate("d-m-Y H:i:s", $UNIX_DATE);
The 86400 is number of seconds in a day = 24 * 60 * 60. The 25569 is the number of days from Jan 1, 1900 to Jan 1, 1970. Excel base date is Jan 1, 1900 and Unix is Jan 1, 1970. UNIX date values are in seconds from Jan 1, 1970 (midnight Dec 31, 1969). So to convert from excel you must subtract the number of days and then convert to seconds
How can I get the first and last day of the last x (I'll replace x by 3, 6 and 12) months ? I know that for the last month will be : date("Y-n-j", strtotime("first day of previous month"));
You can use the DateTime object:
$myDate = new \DateTime("last day of next month");
$format = $myDate->format("Y-n-d");
It returns: 2015-11-30
You can find Relative Formats here: http://php.net/manual/en/datetime.formats.relative.php
Hope it will help you
You already know that a month starts on the 1st. The t specifier to date gives you the number of days in a given month. You can combine the two of those for a given month to determine the first and last day. From there, you would just need to add/subtract 3, 6, and 12 months but that exercise is up to you.
<?php
$first_of_this_month = date("Y-m-01");
$last_of_this_month = date("Y-m-t")
Have a look at this code:
$first = DateTime::createFromFormat('Y-m', '2001-07');
$last = DateTime::createFromFormat('Y-m', '1998-06');
$interval = $first->diff($last);
echo "m diff: ".$interval->m." y diff: ".$interval->y."\n";
The output is m diff: 0 y diff: 3
Why does it return a wrong month difference?
Interesting that if I change dates as '2001-08' and '1998-07', it returns a correct month interval ==1.
Thanks!
PHP DateTime doesn't handle incomplete datetimes.
DateTime::createFromFormat('Y-m', '2011-07') gives a DateTime that has a year of 2011, a month of 7, and a day, hour, minute and second taken from the current time (at the moment I write this, 2011-07-31 18:05:47.
Likewise, DateTime::createFromFormat('Y-m', '1998-06') gives a DateTime that has a year of 1998, a month of 6, and a day, hour, minute, and second taken from the current time. Since June 31st is a nonexistent date, the result is 1998-07-01 18:05:47 (31 days after the day before June 1st).
The difference between those two dates is then 3 years, 0 months, and 30 days.
In your example of 2001-08 and 1998-07, both months happen to have a 31st day, so the math comes out correctly. This bug is a difficult one to pin down, because it depends on the date that the code is run even though it doesn't obviously appear to.
You could probably fix your code by using a format of "Y-m-d H:i:s" and appending "-01 00:00:00" to each date you pass to createFromFormat, which will anchor the DateTime you get back to the beginning of the month.
I know this is old, maybe this may help someone out there:
$first = DateTime::createFromFormat('Y-m', '2001-07');
$last = DateTime::createFromFormat('Y-m', '1998-06');
$interval = $first->diff($last);
$num_months = (($interval->y) * 12) + ($interval->m);
Explanation : convert $interval->y which is the year to months by multiplying it by 12 and add the succeeding months which is $interval->m
I'm trying to format a SQL timestamp in PHP based on the following conditions, but can't figure out how. Can anyone point me in the right direction?
If the timestamp was TODAY, display as 4:15PM or 12:30AM
If the timestamp was before TODAY but in the past 7 DAYS, list as 'Sunday' or 'Monday'
If the timestamp was before 7 DAYS ago, list as 'mm/dd/yy'
How would I go about that?
First you need to convert the MySQL time to a unix timestamp which is what most of php date functions use. If you are using MySQLs DateTime type, you can perform the conversion in SQL with the MySQL function unix_timestamp() mysql date functions. Or you can convert the mysql date to a unix timestamp in PHP with the strtotime($mysqlDateTime) function php strtotime function
once you have the unix timestamp of the time you would like to format, the conversion would look something like this (86400 is number of seconds in 24 hours):
function displayDate($timestamp)
{
$secAgo = time() - $timestamp;
// 1 day
if ($secAgo < 86400)
return date('h:i:A', $timestamp);
// 1 week
if ($secAgo < (86400 * 7))
return date('l', $timestamp);
// older than 1 week
return date('m/t/y', $timestamp);
}
This method has the benefit of not requiring extra object creation in PHP (a tad slow) or performing unnecessary calculations on the SQL server. It might also help to know that MySQL's timestamp type stores data as a unix timestamp (number of seconds since Jan 1 1970) value requiring only 32bits for storage compared to datetime which uses 64bits of storage. 32 bits should be enough for everyone, until 2038 or something....
you can check date difference by by diff() of PHP or by msql datediff()
http://www.php.net/manual/en/datetime.diff.php
Then check difference is zero or equal to 1 or greater than 7
h 12-hour format of an hour with leading zeros 01 through 12 date('H:i:s')
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
G 24-hour format of an hour without leading zeros 0 through 23
USE DATE(G) to find AM or PM
if($TODAY)
date('h:i:s')PM
ELSE IF ($THISWEEK)
l (lowercase 'L') A
full textual representation of the day of the week Sunday through Saturday
ELSE IF($BEFOREONEWEEK)
date('d-m-y')
http://php.net/manual/en/function.date.php
This should work. Hope so :-)
You just have to use a conditional:
$now = new DateTime("now");
$ystrday = new DateTime("yesterday");
$weekAgo = new DateTime("now")->sub(new DateInterval('P7D'));
$inputDate = new DateTime(whenever);
if($yesterday < $inputDate and $inputDate < $now){
$outDate = date('g:ia', $inputDate->getTimestamp() );
}else if($weekAgo < $inputDate and $inputDate < $now){
$outDate = date('l', $inputDate->getTimestamp() );
}else if($inputDate < $weekAgo){
$outDate = date('d/m/y', $inputDate->getTimestamp() );
}
This hasn't been tested and you'll need to get your mySql date into a php DateTime object but it should get you pretty close.
I assume you're talking about the MySQL TIMESTAMP datatype, since I don't think MySQL actually has a datatype like a Unix timestamp (i.e. seconds since epoch), so you'll have to first convert the date you get using the strtotime function:
$timestamp = strtotime($dbTimestamp);
This will return a Unix timestamp you can play with.
Next we'll define a couple more timestamps to compare this value against:
First, we want to know the timestamp for midnight this morning. For that, you'll pass the string "today" to strtotime:
$today = strtotime("today");
Next, we need to know the timestamp for seven days ago. You'll have to choose between "1 week ago" and "1 week ago midnight". The difference between these two is that midnight will return the timestamp for 12am on that day, while the version without it will return the current time, seven days ago (e.g. today, the difference would be that midnight will return 12 AM on April 7 and the non-midnight version would, right now, return 3:45PM on April 7):
$weekAgo = strtotime("1 week ago midnight");
(Note, there are many formats that strtotime understands, including many relative formats like the "today" and "1 week ago" examples used above.)
Next, we need to define the date formats to use in each case:
$timeOnly = "g:i A"; // This gives an "hour:minute AM/PM" format, e.g. "6:42 PM"
$dayOfWeek = "l" // Gives a full-word day of the week, e.g. "Sunday"
$mdy = "m/d/Y" // gives two-digit month and day, and 4-digit year,
// separated by slashes, e.g. "04/14/2011"
Finally, we just do our comparisons, and format our timestamp using the date function:
if ($timestamp >= $today) {
$date = date($timeOnly, $timestamp);
} elseif ($timestamp >= $weekAgo) {
$date = date($dayOfWeek, $timestamp);
} else {
$date = date($mdy, $timestamp);
}
This will leave you with a string variable called $date which contains your database-provided timestamp in the appropriate format, which you can display on your page as needed.