Thank you to anyone who can help. I'm trying to use PHP to get a delivery date that is X days from any given current day. This is to use with the Google Survey Opt-in code and WooCommerce in WordPress.
Referencing this thread: WooCommerce fill-in fields for Google Survey Opt-In Code
Google wants dynamic values, explained here: https://support.google.com/merchants/answer/7106244?hl=en&ref_topic=7105160#example
I have most of the code ready to go, but this dynamic date has been hard to figure out.
I think the simplest solution is to just add a number of days to the day of a product order, which can happen on any given day.
My question is: how do I get PHP to calculate that in this context?
My understanding is that there is DateTime and there is strtotime, but DateTime is the more recent and 'right' way to do this?
This is what I've got so far, but I'm not sure it's right:
//Google Survey code
function wh_CustomReadOrder($order_id) {
//getting order object
$order = wc_get_order($order_id);
$email = $order->billing_email;
?>
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>
<script>
window.renderOptIn = function () {
window.gapi.load('surveyoptin', function () {
window.gapi.surveyoptin.render(
{
"merchant_id": [merchant id],
"order_id": "<?php echo $order_id; ?>",
"email": "<?php echo $email; ?>",
"delivery_country": "CA",
"estimated_delivery_date": "<?php
$inOneWeek = new \DateTime("+7 day");
echo $date->format("Y-m-d");
?>"
}
);
});
};
</script>
<?php
}
add_action('woocommerce_thankyou', 'wh_CustomReadOrder');
You could apply this in the following way, comment with explanation added in the code.
Functions used:
date_i18n() - Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds.
date - Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
Y - A full numeric representation of a year, 4 digits
m - Numeric representation of a month, with leading zeros
d - Day of the month, 2 digits with leading zeros
Also used: "How to get WooCommerce order details"
//Google Survey code
function wh_CustomReadOrder($order_id) {
// Get order object
$order = wc_get_order($order_id);
// Get billing email
$email = $order->get_billing_email();
// Get order date
$date_created = $order->get_date_created();
// Add days
$days = 7;
// Date created + 7 days
$estimated_delivery_date = date_i18n( 'Y-m-d', strtotime( $date_created ) + ( $days * 24 * 60 * 60 ) );
?>
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>
<script>
window.renderOptIn = function () {
window.gapi.load('surveyoptin', function () {
window.gapi.surveyoptin.render({
"merchant_id": [merchant id],
"order_id": "<?php echo $order_id; ?>",
"email": "<?php echo $email; ?>",
"delivery_country": "CA",
"estimated_delivery_date": "<?php echo $estimated_delivery_date; ?>"
});
});
};
</script>
<?php
}
add_action('woocommerce_thankyou', 'wh_CustomReadOrder', 10, 1 );
echo date("Y-m-d", strtotime("+7 day"));
edit: if you don't want today and want an arbitrary date:
$timestamp = 1590097999;
echo date("Y-m-d", strtotime("+7 day", $timestamp));
Related
I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';
Hello guys I'm using to strtotime to convert the date but the problem that I'm facing is it sets the time to 19:00:00 which is wrong. I am sending a date string and then giving it to strtotime and it set the time itself. Right now my time is 11:58 but it is storing the time as 19:00. Please tell me why am I facing this error. Here is the code: strtotime($s_date) $s_date contains only a date string strtotime sets the time
the date string that I'm sending is this 03/04/2016
HTML
<input type="text" class="form-control" id="starts" data-container="#addNewEvent"
data-plugin="datepicker">
Ajax call
$.ajax({
type: "POST",
url: base_url + "apps/calendar/insertCalendar",
async : false,
dataType: 'html',
data: {
'start': $('#starts').val(),
'end': $('#ends').val(),
'title': $('#addTitle').val(),
'description': $('#addDescription').val(),
'type':type
},
success: function(mark_up){
toastr.options = {positionClass: 'toast-top-center'};
toastr.success('Your reminder has been created', 'Reminder created');
window.location.reload();
}
});
Controller Method
public function insertCalendar(){
$s_date = $_POST["start"];
$p = strtotime($s_date);
error_log($p)
}
one thing more I'm stroing it in mongodb so the object that I get from strtotime i convert them into new MongoDate(strtotime($s_date))
First we need to set first timezone
date_default_timezone_set('Asia/Karachi');
then you can get time and date using below code:
echo date('Y-m-d h:i:s'); /* Current date and time*/
echo date('Y-m-d'); /* Current date */
echo date('h:i:s'); /* Current time */
If you want to convert date into required format.
For Example. 03/04/2016, so use
$s_date = '03/04/2016';
echo date('Y-m-d',strtotime($s_date)); /* Convert date into mysql date format */
You will get date according to Y-m-d format of mysql like 2016-03-04.
Now you want user provided date with current time, then you should use
$s_date = '03/04/2016'.' '.date('h:i:s');
echo date('Y-m-d',strtotime($s_date));
This will solve you problem.
I know this question has been asked many times as I have found a few on google and also on stackoverflow.
but none of them explained how to format my datetime in my php so it works in combination with jquery countdown timer. so I am going to ask it here in a hope i get someone shed a light on this for me.
Basically what i am trying to do is to create a countdown timer which will work with mysql datetime.
the datetime is stored in mysql so All need to do is to get the correct format in my php so the countdown timer could work with it.
I am using this plugin: http://keith-wood.name/countdown.html
and here is what i have so far:
PHP formatting:
$end_date = date("m d Y H:i:s T", strtotime($row["end_date"]));
Jquery/Javascript code:
<script type="text/javascript">
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $end_date * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#defaultCountdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds)
{
var message = "";
message += days + " days, ";
message += hours + " hours, ";
message += minutes + " minutes, ";
message += seconds + " seconds ";
message = (finished ? "Countdown finished" : "left untill the New Year");
countdown.html(message);
}
});
});
</script>
when i run this code, all i get is 0 hours, 0 minutes, 0 seconds.
I can only suspect that the issue is from formatting the datetime in my php section!
or am i missing something else as well?
okay I have managed to minify the code to this:
<script type="text/javascript">
$(document).ready(function () {
$('#defaultCountdown').countdown({
until: new Date(<?php echo $end_date; ?>),
compact: true
});
});
</script>
and changed the php to this:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
However, the time shown in the coutdown timer is wrong (way off).
the $end_date is: September 22 2013 23:30:00 GMT in mysql datetime
but the jquery countdown timer is showing:
34d 06:21:48
2013, 9, 22, 23, 30, 00
34days and 6 hours blah blah is absolutely wrong!
what am i doing wrong here now?
The JavaScript Date object is constructed as follows:
Date(year, month, day, hours, minutes, seconds, milliseconds)
That means you probably should be doing something along these lines:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
Sources:
JavaScript Date-object
PHP date-function
EDIT:
In addition, I seem to have found the problem in the jQuery Countdown manual:
A note on Date - the JavaScript Date constructor expects the year,
month, and day as parameters. However, the month ranges from 0 to 11.
To make explicit what date is intended (does a month of 3 mean March
or April?) I specify the month from 1 to 12 and manually subtract the
1. Thus the following denotes 25 December, 2010.
So, you'd have to split the string, substract 1 from the month and rebuild...
$tmp_date = explode(', ', $end_date);
$tmp_date[1] = $tmp_date[1] - 1;
$end_date = implode(', ', $tmp_date);
Link to jsFiddle
basically I know more or less how to do it but would like to know if there is any better way?
I have the following variables in PHP
$day; $month; $year;
The ones above have values from exploding a php date string.
Below is PHP plugin function which states the date for countdown.
<script type="text/javascript">
$(function () {
var austDay = new Date();
austDay = new Date(2013, 12, 22);
$('#defaultCountdown').countdown({until: austDay});
});
</script>
I would like to pass the date day/month/year variables into that function from PHP
how can I do it, when I tried to attach to the javavariable and put that variable in place of the date part, it didnt work.
Thanks for all help
var day = <?php echo $day ?>;
var month = <?php echo $month ?>;
var year = <?php echo $year ?>;
$(function () {
var austDay = new Date();
austDay = new Date( year, month, day );
$('#defaultCountdown').countdown({until: austDay});
});
There's a couple of ways you could skin this.
Fetch the values via $.ajax with php returning the values as a jsonified array (echo json_encode($my_values))
If the page generating the html is a php page then just new Date();
Place the values into hidden form fields anywhere on the page or into data-day, data-month, data-year attributes of a relevant object on the page and fetch the values using jquery
day = $('#hiddenfield_day').val(); //put the var day into the day field of new date, etc
Hope this helps.
Change this line:
austDay = new Date(<?= $year ?>, <?= $month ?> , <?= $day ?>);
That said, keep in mind that Javascript's new Date() month param takes a number in the 0 - 11 range.
I am getting datetime like this 2012-02-06 16:30,2012-02-08 16:45,2012-02-10 16:30 in json.
here is my code.
<script type="text/javascript">
<?php if($this->Date) : ?>
var date = JSON.parse('<?=$this->Date?>');
$.each(date, function(index, value) {
switch(index) {
case 0:
$("#Date").val(value);
$("#Time").val(value);
case 1:
$("#Date1").val(value);
$("#Time1").val(value);
case 2:
$("#Date2").val(value);
$("#Time2").val(value);
}
});
<?php endif; ?>
</script>
here i want to pass date in date filed time in time field.
please help me out
Firstly, I would change the id of #Date and #Time to #Date0 and #Time0 to keep things uniform. That way you can get rid of your switch statement altogether and do something like this, which is much less coding, and expandable for more items without changing the code.
The key to your question is the split() function which will split your date string into an array of pieces.
<script type="text/javascript">
<?php if($this->Date) : ?>
var date = JSON.parse('<?=$this->Date?>');
$.each(date, function(index, value) {
// Split the Date/Time string into an array with two items
//(0=date, 1=time)
var pieces = date.split(' ');
$("#Date"+index).val(pieces[0]);
$("#Time"+index).val(pieces[1]);
});
<?php endif; ?>
</script>
this may work :
var new_arr = [];
var a = "2012-02-06 16:30,2012-02-08 16:45,2012-02-10 16:30".split(",");
for(var i =0; i<a.length; i++)
{
new_arr.push(a[i].split(' '));
}
console.log(new_arr);
var date = '2012-02-06 16:30';
var date_parts = date.split(' ');
# date_parts[0] <- date
# date_parts[1] <- time
if string contains valid date you just can convert it to Date object.
d = new Date("2012-02-06 16:30")
then you should have access to all methods of Date object.
getTime() - Number of milliseconds since 1/1/1970 # 12:00 AM
getSeconds() - Number of seconds (0-59)
getMinutes() - Number of minutes (0-59)
getHours() - Number of hours (0-23)
getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
getDate() - Day of the month (0-31)
getMonth() - Number of month (0-11)
getFullYear() - The four digit year (1970-9999)