Time is wrong when get datetime in yii2 - yii2

I have a problem when I get datetime in my yii2 project. When I get datetime, the date is true but the time is wrong. I execute my code and the result is :
2016-05-02 12:30:28
whereas the time in my laptop is : 19:30. What's the problem? I use time in Indonesia. This is my code:
$time = new \DateTime('now', new \DateTimeZone('UTC'));
$model->tanggal_sampai = $time->format('Y-m-d H:i:s');

First, Find out the timezone for Indonesia from List Of Supported TimeZones - php Manual
Then, make it common for all places using config.php file. Add 'timeZone'=>'Your TimeZone', after components section.
Example : config.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
.
.
.
],
'timeZone'=>'Asia/Kolkata',
'params' => $params,
];

You are asking for the time in the UTC time zone with new \DateTimeZone('UTC'). Either ask for it in your own time zone, which I think is WIB:
$time = new \DateTime('now', new \DateTimeZone('WIB'));
or without a time zone:
$time = new \DateTime('now');

Related

cURL retrieve json data and store in mysql database from url

i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>

How to fix api json delete request

In following code, I'm trying to create a new category (name = 'To be deleted') and then I want to delete it.
first part of the code working fine and I can see new record in the database every time I run the unit test
but I'm having a problem with recode deletion. what's wrong with my code
public function testCategoryDeletion()
{
$user = \App\User::find(1);
//dd($user->name);
$category = \App\Category::create(['name' => 'To be deleted']);
//dd($category->id);
$response = $this->actingAs($user, 'api')
->json('DELETE', "/api/category/{$category->id}")
->assertStatus(200)->assertJson([
'status' => true,
'message' => 'Category Deleted',
]);
}
Test case output
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.
. . . . . . . 7 / 7 (100%)
Time: 1.53 minutes, Memory: 18.00 MB
OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>
In database, recode is created but not deleted,
I fixed the controller as follows and now its working,
public function destroy(Category $category)
{
$status = $category->delete();
return response()->json([
'status' => $status,
'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
]);
}
API routes
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('/task', 'TaskController');
Route::resource('/category', 'CategoryController');
Route::get('/category/{category}/tasks', 'CategoryController#tasks');
});

How to change Template's route by conditions in Controller?

I'm a newbie using cakephp-3.0.
I'm planing to show different templates-views according to user's browser/agent.
In cakephp2.x the code can be like below:
if ($this->DisplayModeService->hasSpViewSupport()) {
App::build([
'View' => [APP . 'View/SmartPhone/', APP . 'View/'],
]);
}
but in cakephp3.0 it's in app.php :
return [
'App' => [
'paths' => [
'templates' => [
APP . 'Template' . DS . 'SmartPhone' . DS,
APP . 'Template' . DS,
],
],
],
];
But I want to change the template route only if the page has smartPhone version.
In the case above it jump into SP version anyway.
(for I wanna keep the same name for the same page )
ex:
/Template/SmartPhone/profile.ctp, /Template/profile.ctp.(has SP/PC Version)
/Template/news.ctp (PC Version only)
can it be possible?
You would better use $this->request->is('mobile'), and Themes

How I can save the moment as timestamp when these lines runs?

$status = db_insert('errors')
->fields( array(
'timestamp' => ???????,
'wid' => $wid,))
->execute();
I want when this line of code running to save the timestamp that will be the moment that this lines will run.. Could someone help me on how to do that thing?
If you literally want the moment that the line was saved, use time().
$status = db_insert('errors')
->fields(array(
'timestamp' => time(),
'wid' => $wid,
));
If you want to save a few processor ticks, and the value is acceptable, you can use Drupal's REQUEST_TIME constant (which is set to the current timestamp at the beginning of each request).
$status = db_insert('errors')
->fields(array(
'timestamp' => REQUEST_TIME,
'wid' => $wid,
));

Wordpress -how to return just current month posts on archive.php

How to modify the wp_query to take in count post by month as per URL 2012/10/ ?
The following will list ALL post, where I just want to list post for 2012/10/
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'posts_per_page' => 10, 'paged' => $paged, 'orderby' => 'date', 'order' => 'DESC' );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
Any suggestions much appreciated.
There's a code snippet provided in the link from the earlier answer that says "Returns posts for just the current week". Change "week" for "month", and you got your answer.
The code snippet would look like this:
$year = date('Y');
$month = date('n');
$query = new WP_Query( 'year=' . $year . '&monthnum=' . $month );
Just read the link. It's all there.
EDIT: If there are further problems returning the month, it may be because the variable needs a leading zero. In that case, the $month variable should be
$month = date('m');
You can do that with the year and monthnum parameters, as described in the section Time Parameters in the class reference:
// ... set up your argument array for WP_Query:
$args = array(
'posts_per_page' => 10,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC' ,
// add the year/month query here:
'year' => 2012,
'monthnum' => 10
);
$wp_query = new WP_Query($args);
// ... and so on