How to compare DateTime in Extbase repository - typo3

I try to compare the start date of an event with the current date in order to only display the next events. This is my try in the eventRepository:
public function findNext() {
$query = $this->createQuery();
$query->matching(
$query->greaterThanOrEqual('datum_beginn', new \DateTime('midnight'))
);
return $query->execute();
}
But the result is not as expected. This is the resulting query:
SELECT events.* FROM events WHERE events.datum_beginn >= 1413669600 AND ...
As you can see the DateTime is converted to a timestamp. How can I either use MySQL NOW() in the query OR use DateTime properly?

Use string value of the date:
public function findNext() {
$query = $this->createQuery();
$date = new \DateTime('midnight');
$query->matching(
$query->greaterThanOrEqual('datum_beginn', $date->format('Y-m-d H:i:s'))
);
return $query->execute();
}

In 9 LTS it is possible to compare against DateTime directly:
$query->greaterThanOrEqual('datum_beginn', new \DateTime)

Related

JPA-Query for a Date in a Datetime column

I'm trying to build a query for all orders which were created today.
My Order-Entity has a datetime field like this:
#Column(name = "OrderCreationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date orderCreationDate;
Named-Query:
#NamedQuery(name = "OrderHeader.findByOrderCreationDate", query = "SELECT o FROM OrderHeader o WHERE o.orderCreationDate = :orderCreationDate")
I tried to build the query like this:
public List<OrderHeader> findFromToday() {
Date dateToday = new Date();
TypedQuery<OrderHeader> query = em.createNamedQuery("OrderHeader.findByOrderCreationDate", OrderHeader.class).setParameter("orderCreationDate", dateToday);
return query.getResultList();
}
Of course the ResultList is empty since the date AND time would have to match.
Unfortunately I need the time in my database, so the orderCreationDate needs to stay datetime/timestamp.
So how can I query for a specific date, ignoring the time?
thanks!
Your call to setParameter needs to pass in the temporal type argument also, defining what to use for comparison.
http://www.datanucleus.org/javadocs/javax.persistence/2.1/javax/persistence/Query.html#setParameter-java.lang.String-java.util.Date-javax.persistence.TemporalType-

Mirth Connect SQL Server Error : Conversion failed when converting date and/or time from character string

I am trying to insert into SQL Server DateTime field. Trying simple scenario of one table having datetime column named start_date only.
Query I am trying is
INSERT INTO test (start_date) values (${start_date})
start_date is channelMap variable of Type java.util.Date , It was created using :
var start_date = DateUtil.getDate('yyyyMMddHHmmss', msg['date'].toString());
Here start_date is of java.util.Date, why mirth treats it as String when it tries to insert into database ??
You can handle the conversion even in SQL. Hope it helps
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
try {
sql="INSERT INTO test (start_date) values (convert(datetime,'" + start_date + "',5))";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
Out in DB will be below.
select * from test
start_date |
----------
1983-11-23 00:00:00.000
2nd Approach
If you still want to use util try below
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
/*
Input is yyyyMMdd and
output is yyyyMMddHHmmss format
*/
var datestring = DateUtil.convertDate('yyyyMMdd', 'yyyyMMddHHmmss', start_date);
try {
sql="INSERT INTO test (start_date) values ('" + start_date + "')";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
I believe your data is inserting in DB as 'Mon Feb 19 09:25:16 IST 1968' along with quotes.
I used formatDate function, but data inserted into DB will be like 1968-02-19 09:25:16
var pidDate = msg['PID']['PID.7']['PID.7.1'].toString();
var value = DateUtil.getDate("yyyyMMddHHmmss",pidDate);
var data = DateUtil.formatDate("yyyyMMddHHmmss", value)
channelMap.put("start_date",data);
Inserting to DB:
var dateValue = $('start_date')
dbConn = DatabaseConnectionFactory.createDatabaseConnection(dbDriver, dbAddress, userName,passwd);
result = dbConn.executeUpdate("INSERT INTO test (startdate) values ('"+dateValue+"')");
I'm sending date value as 19680219092516,inside DB value is 1968-02-19 09:25:16.Datatype of my DB is DateTime type.
the getDate function returns a java.util.Date object, but when I tried with getCurrentDate function, it returns a formatted String. I guess formatting the date object is one way of inserting data into DB.

ascending order by a.bill_id id in array_merge in codeigniter?

$this->db->select('b.name as user_name,a.bill_id,a.dat,a.bill_id,a.buyer_typ');
$this->db->from('tra_books_sales_head a');
$this->db->join('mas_staff_head b','b.staff_id = a.staff_id');
$query1 = $this->db->get()->result();
$this->db->select('a.customer_name as user_name,a.bill_id,a.dat,b.bill_id,a.buyer_typ');
$this->db->distinct();
$this->db->from('tra_books_sales_head a');
$this->db->join('tra_books_sales_dt b','b.bill_id = a.bill_id');
$this->db->where('a.customer_name is not NULL');
$query2 = $this->db->get()->result();
return $query =array_merge($query1,$query2);
how can i get ascending order above this query.
order by a.bill_id
You can use $this->db->order_by();. Try:
$this->db->order_by('a.bill_id','asc');
If you want to order elements after array_merge you should use array_multisort, you can read more about it here

MONGODB AND LARAVEL 5.1. I need to get all the documents updated today, how can I do that?

I need to get all the documents where updated_at is the same date a today or yesterday,
how can I do that?
This is my current code:
$yesterday = new DateTime('-1 days');
$yesterday = $fecha->format('Y-m-d');
$yesterday = new MongoDate(strtotime($yesterday.'00:00:00'));
$date=CampaignLog::where('campaign_id',$id)->where('updated_at','=', $yesterday)->get(array('data'));
Laravel's Eloquent supports Carbon/DateTime objects instead of MongoDate objects which will be converted internally to MongoDate objects when saved to the database. You could use this date handling package in laravel called Carbon with your queries.
For example, if you want to query for records from CampaignLog data where a mongodb datetime field updated_at is greater that a given date, say records from yesterday, use Carbon's yesterday() helper method:
$dt = Carbon::yesterday();
$campaigns = CampaignLog::where('updated_at', '>=', $dt)->get();
Similarly, to do a data range query i.e. query for records between a now and yesterday, use the whereBetween method:
$campaigns = CampaignLog::whereBetween(
'updated_at', array(
Carbon::yesterday(),
Carbon::now()
)
)->get();
Another approach would be to use Eloquent which allows you to work with Carbon/DateTime objects instead of MongoDate objects. Example inspired from the docs:
<?php
use Jenssegers\Mongodb\Model as Eloquent;
class CampaignLog extends Eloquent {
use SoftDeletingTrait;
/**
* Collection for Model
*
* #var String
*/
protected $collection = "campaignlogs";
/**
* Connection for model
*
* #var type
*/
protected $connection = 'mongodb';
protected $dates = array('updated_at');
}
Which allows you to execute queries like:
$campaigns = CampaignLog::where('updated_at', '>=', new DateTime('-1 day'))->get();
Or natively using MongoDate objects, you could try
$start = new MongoDate(strtotime("yesterday"));
$stop = new MongoDate();
$campaigns = DB::collection('campaignlog')->whereBetween('updated_at', array($start, $stop))->get();

Trying to get month from date in laravel (and postgres extract not working)

I'm making my first laravel project, using postgres, and I'd like to be able to access all the people with a birthday this month (my people table has a birthdate field that's a date). I can use extract to get these records from the database, like so:
select * from people
where extract (month from birthdate) = 11;
But when I try a few different ways in my controller I get 'unknown column' errors:
$birthday_people = DB::table('people')
->where ("extract(month from birthdate)", "=", "11")
->get();
(I'll ultimately adjust it to compare with Carbon::now()->month, and use the model Person::all(), but until I get some results coming through I'm going as simple as possible)
Is there a special way to get the month from a date in laravel?
Update: I'm using a scope now in my Person model. I can get person results to come through when I give it an exact date:
public function scopeBirthdays($query)
{
return $query->where('birthdate', '=', '1947-11-02');
}
And I can get results back for month if I do it this way, but the catch is it doesn't seem to know it's a collection of People anymore (I can't access person columns when I display it out and I can't chain other scopes):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}
Laravel's query builder offers 'whereMonth'- (seems the most right), but it gave me an 'undefined function' error until I put the bool on the end, and now the current error suggests that it's interpretting number of months instead of which one(?):
public function scopeBirthdays($query)
{
return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}
I get:
Syntax error: 7 ERROR: syntax error at or near "month"
LINE 1: select * from "people" where 1 month("birthdate") = $1
^ (SQL: select * from "people" where 1 month("birthdate") = 11)
Final update: I was able to get results back (that were correctly interpretted as people) by using whereRaw in my scope:
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}
Thanks, everyone!
based on previous question try:
$birthday_people = DB::table('people')
->whereRaw("extract(month from birthdate)", "=", "11")
->get();
You can set is as relationship
public function custom(){
return $this->hasMany('App\Models\People')->whereRaw("extract(month from birthdate)", "=", "11");
}
You could try something like this. It will return as an instance of App\People so you will be able to use your eloquent functions still.
public function scopeBirthdays($query)
{
return $query->where('birthdate', 'LIKE', Carbon::today()->year . '-'.Carbon::today()->month.'%');
}
I don't have much experience with Carbon, I'm assuming that Carbon::today() will return an object with the year, month, and date.