Query a timestamp in MongoDB by just the date part of timestamp - java

I want to return a list of Documents that have a timestamp for a specific date. However, the timestamp also contains the time. Is there a method to filter by just the date part of the timestamp?
timestamp: 2022-10-27T11:11:07.350+00:00
Query method:
public static Query getEventByDateQuery(final String date) {
return Query
.query(
where("timestamp").......
);
}

Related

Parametrized query request postgresql

I want to get data from my DB where is LocalDateTime equals to LocalDateTime in get request.
#Override
public List<Timeslot> getAllAvailable(LocalDateTime localDateTime) {
return jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER);
}
Timeslot table code:
CREATE TABLE "timeslot" (
"timeslot_id" serial,
"day" date NOT NULL,
"start_time" TIME NOT NULL,
"end_time" TIME NOT NULL,
"user_id" serial NOT NULL,
"is_recorded" boolean,
CONSTRAINT "timeslot_pk" PRIMARY KEY ("timeslot_id")
);
Controller code:
#GetMapping("/allAvailable")
public List<Timeslot> getAllAvailable(#RequestParam("day") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime day) {
return userService.allAvailable(day);
}
But when I did this request result in console is: org.postgresql.util.PSQLException: ERROR: syntax error at end of input. How do i change sql request code to fix this error? Should I use PrepareStatement or something else?
As #AndrewS mentioned, you didn't pass localDateTime value as parameter. Therefore jdbcTemplate doesn't bind ? to localDateTime.
You should use overloaded method of query and pass localDateTime as the last parameter:
jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime);
I think you are storing day as Date format in the database. and in the query you are comparing day whose type is Date with LocalDateTime type which might be wrong. first take Date from LocalDateTime then pass as method argument. For example
jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime.toLocalDate());

Sqlite : Comparing timestamp value stored in a column to current Date

I store information in a sqlite database table as follows:
ActionDate column is of type : DEFAULT CURRENT_TIMESTAMP
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I want to write an SQL query that returns all rows in my table having ActionDate value as today's date from sqlite DB. However as ActionDate is of type timestamp what is the most appropriate way to convert it to todays date.
If you want current date then use the following query :
SELECT date('now');
To get all columns in your table having ActionDate equal to todays date use the below query :
select * from table where strftime('%Y-%m-%d ', datetime(ActionDate, 'unixepoch')) = date('now)' ;
more info on SQLite Date & Time queries can be found here

Datetime in HQL check only date

I've the following hql query:
Query query = session.createQuery("from Appointments where datetime < :now");
query.setDate("now", new Date());
listApps = query.list();
It return only the records before today (yesterday, 2 days ago and so on)
But not the record of today before than this time.
The datetime into the database is of type DateTime, so it contains both date and time.
Why is this query not returning the record of today before than the current time?
This is the way datetime is defined inside my entity:
#Temporal(TemporalType.TIMESTAMP)
private Date datetime;
Change from
query.setDate("now", new Date());
to
query.setTimestamp("now", new Date());
or to:
query.setParameter("now", new Date());
Bind the date (time is truncated) of a given Date object to a named query parameter.
public Query setDate(String name, Date date);
Bind the date and the time of a given Date object to a named query parameter.
public Query setTimestamp(String name, Date date);

Date - Java to Sql table and sql table to Java through Joda Time

I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());

Criteria query for fetching the data after particular date and time

I am using the criteria query as follows:I want to fetch the reservations after the time and date I have passed.but now i am getting the reservation before the time which i have passed for the same date.Please help..
#GET
#Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(#PathParam("userid") int uid, #PathParam("type") int tid,#PathParam("date") Date date,#PathParam("time") Time time) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
Root<Reservation> r = criteria.from(Reservation.class);
TypedQuery<Reservation> query = em.createQuery(
criteria.select(r).where(new Predicate[]{
builder.equal(r.get(Reservation_.usersId), uid),
builder.equal(r.get(Reservation_.reservationsType), tid),
builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
return query.getResultList();
}
Comparing dates and times formatted as string is not advisable, results can depend on the format. It would be better having a unique Date field in the Reservation class:
#Temporal(TIMESTAMP) Date date;
and using date comparison in the query:
builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)
This way the time parameter in the getReservationByAndUserIdAndTypeAndDateTime method can be omitted, since the date parameter would hold both date and time.

Categories