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.
Related
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));
Here my jquery ajax request,
I m trying to send selected date or manually increasing days values to the controller
function myFunction(selected_first_date){
var get_my_value = $('#get_my_value').val();
$.ajax({
url :"<?php echo base_url();?>index.php/holiday_package_controller/PackageController/dateChangerFunction",
type:"POST",
data:{
get_my_value:get_my_value,
selected_first_date:selected_first_date
},
dataType: "json",
success: function(data){
//$('#cash_receipt_voucher_date').html(data);
console.log(data);
$('#incremented_date').val(data.incremented_date);
}
});
}
Controller
$get_my_value = $this->input->post("get_my_value");
$selected_first_date = $this->input->post("selected_first_date");
if(!empty($selected_first_date)){
for($i=0; $i<=$get_my_value; $i++)
$repeat = strtotime("+$i day",strtotime($selected_first_date));
$rdate = date('Y-m-d',$repeat);
print_r($rdate);
exit();
}
I like the DateTime class for things like this https://3v4l.org/g9v53:
<?php
$date = new DateTime('2014-09-18 10:00:00');
$date->modify('+12 hours');
echo $date->format('Y-m-d H:i:s');
2014-09-18 22:00:00
Here are all the relative modification formats from the docs:
https://secure.php.net/manual/en/datetime.formats.relative.php
If the date time you are sending is not in 'Y-m-d H:i:s' format, then use DateTime::createFromFormat($customFormat, $dateTimeString);
As per your code above, first please remove the exit() from the loop as it will terminate the script in first iteration, so put exit() outside like
for($i=1; $i<=$get_my_value; $i++) {
$repeat = strtotime("+$i day",strtotime($selected_first_date));
$rdate = date('Y-m-d',$repeat);
print_r($rdate);
}
exit();
Also I've changed $i to starts from 1 so it will treat it as +1 Day in strtotime for selected date. Keep print_r($rdate) as it is then check output.
$date_frm_soap = '2015-12-16T22:14:04-0700';
date_default_timezone_set("PS8PDT");
from this how can i calculate the date based on the timezone set.
I tried the below as it is calculating time based on the time zone but
strtotime($date_frm_soap) how we can convert this to UTC date format.
Links which helped me:
convert soap time in PHP
Convert Date in PHP to XMLGregorianCalendar format and back
You can use the DateTime object, it is incredibly flexible and will recognise almost any data format you throw at it. You then set a timezone into the DateTime object and then print a formatted date in whatever format you want to see it in.
<?php
$date_frm_soap = '2015-12-16T22:14:04-0700';
// load the DatTime object with your date
$date = new DateTime($date_frm_soap );
// tell DateTime we want to use UTC
$date->setTimezone(new DateTimeZone('UTC'));
echo 'in date = '. $date_frm_soap . PHP_EOL;
// output the data in which ever format you want to see it in
echo 'UTC date = '. $date->format('Y-m-d H:i:s');
This produces these results
in date = 2015-12-16T22:14:04-0700
UTC date = 2015-12-17 05:14:04
I'm trying to figure out how to accept a date/time from a form, which is consequently in the user's timezone, and change it to UTC before inserting it into the database. For some reason, no amount of searching has netted me an answer.
My form will POST whatever date is selected by the user to my code, so I expect to be able to do something like this. Note: the $userDate may be relative to any number of timezones based on user's location
$userDate = $_POST['user_date'] // 2014-05-15 16:37:23
I anticipate using Date().getTimezoneOffset() on my form to also submit the users UTC offset (as detailed here).
$userOffset = $_POST['user_offset']
Then before inserting the date into my database, I would like to convert it to UTC -- but I am stumped on how to do that with PHP (I'm actually using Laravel so if you know of a way using Carbon, that would be even easier, but I couldn't find it in their docs).
I've been half tempted to manually parse the offset and convert it to number of seconds and add or subtract it to strtotime() output of the $userDate and then convert it back into a date format using date() -- but there has to be a better way!
What am I missing here? Does PHP have a function I just don't know about that lets me do something like:
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$utcDate = date_apply_offset($userDate, $userOffset);
echo $utcDate; // Outputs: 2014-05-15 20:37:23
Or am I making this harder than it has to be?
EDIT
Based on the solution provided by #vascowhite, I went with the following (added into question to improve answers for those seeking guidance)
I ended up using a function from moment.js since I was already using it to convert UTC to user's timezone on display.
HTML:
<input id="user_offset" type="hidden" name="user_offset" value="">
Javascript:
var offset = moment().format('ZZ');
$('#user_offset').val(offset);
PHP (in a custom date class):
class MyDate {
/**
* Convert Date to UTC
*
* #param string $date Any date parsable with strtotime()
* #param string $offset UTC offset of date
*/
public static function toUTC($date, $offset = '+0:00')
{
if ($timestamp = strtotime($date) && ! empty($offset) )
{
$newDate = date('Y-m-d H:i:s', $timestamp);
$newDate = new \DateTime($date . ' ' . $offset);
$newDate->setTimezone(new DateTimeZone('UTC'));
$date = $newDate->format('Y-m-d H:i:s');
}
return $date;
}
}
// To convert
$userDate = trim($_POST['user_offset']);
$userOffset = trim($_POST['user_date']);
$utc = MyDate::toUTC($userDate, $userOffset)
That class method isn't perfect, and in the event something goes wrong, it just returns the date back -- when really it should throw an exception.
This is a simple task with the DateTime classes:-
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$date = new \DateTime($userDate . ' ' . $userOffset);
var_dump($date);
$date->setTimezone(new \DateTimeZone('UTC'));
var_dump($date);
You can then format the date as you wish for output eg:-
echo $date->format('Y-m-d H:i:s');
or:-
$utcDate = $date->format('Y-m-d H:i:s');
echo $utcDate; // Outputs: 2014-05-15 20:37:23
See it working.
If you are doing any work with dates and times in PHP it is worth taking the time to become familiar with these extremely useful classes.
For all sorts of date/time manipulations you can make use of moment.php
For your example all what is needed are two lines of code:
$m = new \Moment\Moment('2014-05-15 16:37:23', '+0400');
echo $m->setTimezone('UTC')->format(); // 2014-05-15T12:37:23+0000
There is much more which helps to deal with date/time issues: https://github.com/fightbulc/moment.php
Cheers
Im using JQuery Full Calendar Plugin. Code:
$('#mycalendar').fullCalendar({
** options **
events: function(start, end, callback) {
$.ajax({
url: '/myloader/',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000)
}
*** more stuff
});
now on myloader php side when i try to get start and end dates here is what i get:
var_dump(date('m/d/Y H:i:s', $_GET['start']), date('m/d/Y H:i:s', $_GET['end']));
this returns:
string(19) "01/27/2013 06:00:00"
string(19) "03/10/2013 06:00:00"
why is it 6:00:00 ? i want it to be 00:00:00 for start and 23:59:59 for end
I know i can hack through it using PHP but is there a reason why full calendar returns such date?
If i use PHP i can get desired results using:
$start = strtotime(date('m/d/Y', $start) . ' 00:00:00');
$end = strtotime(date('m/d/Y', $end) . ' 23:59:59');
but i dont want to do it on PHP side is there a way full calendar to give correct time?
If its a timezone issue how can it be fixed?
thanks
How about this:
var_dump(
date('m/d/Y H:i:s', strtotime(date("m/d/Y",(int)$_GET['start'])),
date('m/d/Y H:i:s', strtotime(date("m/d/Y",(int)$_GET['end']))
);