Echo variables in correct order - php

Set-up
I've decided to try a little bit of PHP myself, I'm a total beginner.
I run a WooCommerce shop and want to dynamically display the expected delivery date range on each product page.
The delivery date range is today's date plus 3 and plus 4 days, e.g. today is the of 10th October so the delivery date range is 13 and 14 October. On each product page it should therefore mention,
Delivery between Oct 13 and Oct 14
I know where to write the code such that it displays where I want it to appear on the product pages.
I also know how to dynamically update the delivery dates.
Problem
Echo mixes the variables, instead of,
Delivery between Oct 13 and Oct 14
it states,
Delivery between and Oct 13Oct 14
My Code
function my_custom_action() {
$plus3 = strtotime("+3 day");
$plus4 = strtotime("+4 day");
$date_low = date('M d', $plus3);
$date_high = date('M d', $plus4);
$start_text = _e('Delivery between ','woodmart');
$end_text = _e(' and ','woodmart');
echo $start_text, $date_low, $end_text, $date_high ;
};
add_action( 'woocommerce_single_product_summary', 'my_custom_action', 15 );
I need $start_text and $end_text in functions so the strings are translatable.
Preferably I also have the months (e.g. Oct) translatable, but for now I'd already be very happy to know how I get all variables echoed in the desired order.

This can be resolved using string interpolation.
for eg.
$name = "PHP";
echo "I am reading {$name}POT";
// output: I am reading PHPPOT
here's the link to a much more detailed reference : variable-interpolation-in-php

Related

How can I extract and display separate day/month/year from user supplied PHP date format string?

I have a custom blog module in WordPress. The user is allowed to specify whatever PHP date format they want when configuring the module. For example, 'j m Y'.
The module outputs the day, month and year on separate lines. It currently defaults to using the 'd F Y' format. So that July 6, 2018 would display as follows:
06
JUL
2018
<?php
// If we have chosen to show a date, get individual date components for style 4
if ( 'on' === $show_date ) {
$ci_post_date = get_the_date( );
$ci_post_day = date('d', strtotime( $ci_post_date ) ); // 01 - 31 day format
$ci_post_month = date('M', strtotime( $ci_post_date ) ); // 3 character month format (Jan - Dec)
$ci_post_year = date('Y', strtotime( $ci_post_date ) ); // 4 digit year format
?>
<div class="ci-date post-meta">
<span class="ci-day"> <?php echo $ci_post_day ?> </span>
<span class="ci-month"><?php echo $ci_post_month ?></span>
<span class="ci-year"> <?php echo $ci_post_year ?> </span>
</div>
<?php
}
The spans above are formatted via CSS to show on separate line. This also allows the user to have their own custom CSS for each date portion.
There is also a variable, $meta_date, that will hold the user supplied date format string. But I don't know how to extract the supplied format for each date component so that I can echo it correctly.
I am not able to figure out how to format each of those three lines based on that user supplied format string. Any examples I have seen on all the PHP documentation and here in Stack all assume that the date format is known. Hard-coded, if you will.
I'd like to display the day of the month on one line, using the user supplied format string. And so forth with the month and year on each line.
So, if the user supplied the above example j m Y format, I need to be able to display the date as such:
6
07
2018
I can't figure out how to see what the day of the month portion of the date format string is, and then display the day of the month (only) in that format.
For example, how can I extract the day portion of the user supplied format so that I can modify this line:
$ci_post_day = date('d', strtotime( $ci_post_date ) ); // 01 - 31 day format
My question is how I determine what value to use in place of 'd' in the above line if the user has supplied another format for the day of month.

Wrong month printed on last day of August

I had this bug yesterday (August 31st) where the following printed out...
$timezone = new DateTimeZone('Europe/Helsinki');
$calendar_month_name = DateTime::createFromFormat('m', 9, $timezone)->format('F');
echo $calendar_month_name; // returns October
echo date('M'); // returns August
However, when the date changed to the 1st September, $calendar_month_name corrected itself.
Anyone know why this was? Thanks.
Edit I've turned my calendar back to be on the 31 Aug again, which is why echo date('M'); returns August.
Edit 2 Here is an example using date()
date_default_timezone_set('Europe/Helsinki');
echo date('F', mktime(0,0,0,9)); // returns October
In one line you are asking the name of the month 9 which is September.
On the last line you are asking the short name of the current month.
I think that this is what you intend, isn't?
$calendar_month_name = DateTime::createFromFormat('m', date('m'),$timezone)->format('F');
Cheers!

Unrecognized Date format

Good !
I am having some difficulties with extracting data from a date. The thing is that I get a number from an undocumented API.
"created": 734394
"last_chapter_date": 734883
I tried dividing it by 365,242 days (exact amount of days a year)
2010,705231052289
So apparently these are the number of days passed since 0.0.0000
I am currently trying something like that:
http://jsfiddle.net/LRUy5/4/
function zero21970(nDays) {
// 0 70 2013
// |-----|-----|
// 0 to date
var dateMils = nDays*24*60*60*100;
// 0 to 1970
zeroTo1970 = (1970*365.242)*24*60*60*100;
//subtract time from 0-1970 from the time 0-date
//to cut out the part from 1970-today
return new Date(dateMils-zeroTo1970);
}
//http://www.mangaeden.com/api/manga/4e70e9f6c092255ef7004344/
zero21970(734394) //-> Jan 26 1974
I need to save it in a database and work with it via php or javascript..
Does anyone recognize this kind of format or do you know a convenient way of formatting it?
Edit: I should add that the last chapter came out around 15.01.2013.. just to have something to grab.
Updated version:
I guess if the last chapter was from 2013, then the value is a number of days from 01.01.0001. So we can update the initial date as well as change setHours to setDate method for more accuracy:
var date = new Date("0001");
date.setDate(734883);
date.toGMTString(); // "Tue, 15 Jan 2013 00:00:00 GMT"
DEMO: http://jsfiddle.net/LRUy5/6/
Old version:
I found one solution that successfully works at my computer:
var date = new Date("0000");
date.setHours(734394 * 24);
date.toGMTString(); // "Mon, 13 Sep 2010 21:00:00 GMT"
DEMO: http://jsfiddle.net/LRUy5/5/
If you're using PHP, then you should replace
return new Date(dateMils-zeroTo1970);
with
return date('Y-m-d', (dateMils-zeroTo1970));

Can't get previous month from DateTime in PHP- Is this a (pretty big) bug?

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)

Find out date of nth week's monday in PHP?

I have a simple situation where I have a user supplied week number X, and I need to find out that week's monday's date (e.g. 12 December). How would I achieve this? I know year and week.
Some code based mainly on previous proposals:
$predefinedYear = 2009;
$predefinedWeeks = 47;
// find first mоnday of the year
$firstMon = strtotime("mon jan {$predefinedYear}");
// calculate how much weeks to add
$weeksOffset = $predefinedWeeks - date('W', $firstMon);
// calculate searched monday
$searchedMon = strtotime("+{$weeksOffset} week " . date('Y-m-d', $firstMon));
An idea to get you started:
take first day of year
add 7 * X days
use strtodate, passing in "last Monday" and the date calculated above.
May need to add one day to the above.
Depending on the way you are calculating week numbers and the start of the week this may sometimes be out. (i.e. if the monday in the first week of the year was actually in the previous year!)
TEST THIS THOROUGHLY - but I've used a similar approach for similar calcualtions in the past.
This will solve the problem for you. It mainly derives from Mihail Dimitrov's answer, but simplifies and condenses this somewhat. It can be a one-line solution if you really want it to be.
function getMondaysDate($year, $week) {
if (!is_numeric($year) || !is_numeric($week)) {
return null;
// or throw Exception, etc.
}
$timestamp = strtotime("+$week weeks Monday January $year");
$prettyDate = date('d M Y');
return $prettyDate;
}
A couple of notes:
As above, strtotime("Monday January $year") will give you the timestamp of the first Monday of the year.
As above +X weeks will increment a specified date by that many weeks.
You can validate this by trying:
date('c',strtotime('Sunday Jan 2018'));
// "2018-01-07T00:00:00+11:00" (or whatever your timezone is)
date('c',strtotime('+1 weeks Sunday Jan 2018'));
// "2018-01-14T00:00:00+11:00" (or whatever your timezone is)
date('c',strtotime('+52 weeks Sunday Jan 2018'));
// "2019-01-06T00:00:00+11:00"
Due to reputation restriction i can't post multiple links
for details check
http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.mktime.php
you can use something like this :
use mktime to get a timestamp of the week : $stamp = mktime(0,0,0,0,<7*x>,) {used something similar a few years back, so i'm not sure it works like this}
and then use $wDay = date('N',$stamp). You now have the day of the week, the timestamp of the monday should be
mktime(0,0,0,0,<7*x>-$wDay+1,) {the 'N' parameter returns 1 for monday, 6 for sunday}
hope this helps
//To calculate 12 th Monday from this Monday(2014-04-07)
$n_monday=12;
$cur_mon=strtotime("next Monday");
for($i=1;$i<=$n_monday;$i++){
echo date('Y-m-d', $cur_mon);
$cur_mon=strtotime(date('Y-m-d', strtotime("next Monday",$cur_mon)));
}
Out Put
2014-04-07
2014-04-14
2014-04-21
2014-04-28
2014-05-05
2014-05-12
2014-05-19
2014-05-26
2014-06-02
2014-06-09
2014-06-16
2014-06-23

Categories