Spring MongoDB - Finding Documents between two dates - java

I am somewhat new to Java and am trying to write a query which will return the documents stored in my mongodb between two dates. I think I am close to getting it correct but am having a hard time getting there. I am receiving the date ranges in the following format:
[2017-06-29, 2017-07-05]
The dates that i am comparing are stored in the database as follows:
yyyy-MM-dd'T'HH:mm:ss-SSSS
What i have so far..
public List<VehicleStatus> getReportingDateRange(List<String> dates) {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss-SSSS");
Date startDate = outputFormat.parse(dates.get(0));
Date endDate = outputFormat.parse(dates.get(1));
Query query = new Query();
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(outputFormat.format(startDate)),
Criteria.where("updateTime").lte(outputFormat.format(endDate)));
query.addCriteria(c);
return this.mongoOperations.find(query, VehicleStatus.class);
}
I am receiving a parse Exception. I am really not sure where to go from here, any help is greatly appreciated. If you need any additional information please let me know.
Thank you!

You will need to parse the date into input format followed by formatting the date to output format.
Something like
String startDate = outputFormat.format(inputFormat.parse(dates[0]));
String endDate = outputFormat.format(inputFormat.parse(dates[0]));
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(star‌​tDate), Criteria.where("updateTime").lte(endDate));
You should try to save the date as date type and use below version.
Date startDate = inputFormat.parse(dates.get(0));
Date endDate = inputFormat .parse(dates.get(1));
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(star‌​tDate), Criteria.where("updateTime").lte(endDate));

Related

Get Now Date and Time

I'm using JPA and I want to store the date in this format dd/MM/yyyy HH:mm:ss
So I create a function
public static String getNowDate() {
Date date = new Date();
final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return sdf.format(date);
}
The problem is that this returns a String and I need a date.
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
How do I make this work so I can save date and time exactly like that?
I know a easy solution is to declare creationDate as String. Is this too bad?
There is a problem with the premise to your question. Ideally, your current timestamp will be stored in a SQL database, in some sort of date column, and not as text. Since you are using JPA, backed by JDBC, you should just be inserting a date type. So, something like the following should work:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// or maybe just
Date now = new Date();
Then, just let JPA worry about how to martial the current timestamp into your database table. If you really need to format your timestamp as shown, then worry about this in your Java code somewhere.

MySql Date read incorrectly using getDate

I have two date fields in my mysql db.
They look like so in my db.
When I pull them into java using resultSet.getDate I get the following dates in java...
29/01/2016 00:00:00,3/01/2016 00:00:00
My mapping code is below...
masterList.setRpmPromoCompDetailStartDate(resultSet.getDate(DaoConstants.COLUMN_HEADER_RPM_PROMO_COMP_DETAIL_START_DATE));
masterList.setRpmPromoCompDetailEndDate(resultSet.getDate(DaoConstants.COLUMN_HEADER_RPM_PROMO_COMP_DETAIL_END_DATE));
Where my domain object looks like this...
public class MasterList {
private Date rpmPromoCompDetailStartDate;
private Date rpmPromoCompDetailEndDate;
Everything in the output looks right except the month. Can anyone give me some advice on what might be wrong?
thanks
EDIT
Here is my attempted fix...
Timestamp startDateTs = resultSet.getTimestamp(DaoConstants.COLUMN_HEADER_RPM_PROMO_COMP_DETAIL_START_DATE);
java.util.Date startDate = null;
if (startDateTs != null){
startDate = new java.util.Date(startDateTs.getTime());
}
masterList.setRpmPromoCompDetailStartDate(startDate);
Timestamp endDateTs = resultSet.getTimestamp(DaoConstants.COLUMN_HEADER_RPM_PROMO_COMP_DETAIL_END_DATE);
java.util.Date endDate = null;
if (endDateTs != null){
endDate = new java.util.Date(endDateTs.getTime());
}
Use resultset.getTimeStamp to get date
java.util.Date date;
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
date = new java.util.Date(timestamp.getTime()));

Java util.numberFormatException for input string: "2014-01-12 05-44-56"

I'm new in OFBiz, and Java. I used bellow block of code for checking date time input and use that for searching in table.
Timestamp strtDate = UtilDateTime.getTimestamp((String)request.getParameter("strt_date"));
if(strtDate != null)
{
// then here i used the date for taking data.
}
When i fill the date time field of form to search or when no date is selected for searching error occure that show numberFormatException, so how i can solve that? thanks for any help and guide.
Based on the Apache ofbiz API it looks like UtilDateTime#getTimestamp(String) expects milliseconds value. You are passing in "2014-01-12 05-44-56". You need to parse your date first. With pure pre 1.8 java (keep in mind that formatters aren't thread safe):
String dateString = "2014-01-12 05-44-56";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date = formatter.parse(dateString);
UtilDateTime.getTimestamp(date.getTime());
Since java 1.8 (highly recommended to switch if you can!):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
ZonedDateTime date = ZonedDateTime.parse(text, formatter);
long millis = date.toInstant().toEpochMilli();
you have to pass time in milliseconds not as you are passing.
you can check code also :
public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
return new Timestamp(Long.parseLong(milliSecs));
}
it will parse the data in long which you are passing and that should be valid long value.
request.getParameter("strt_date") will anyways return String, so no need to cast it explicitly to String. Moreover, there will be a contract between Client & Server on the required Date Format. So you have to parse the String-Date in the same format using SimpleDateFormat. Code outlook will look like bellow:
SimpleDateFormat formatter = new SimpleDateFormat("contract-date-format");
Date date = formatter.parse(request.getParameter("strt_date"));
UtilDateTime.getTimestamp(date.getTime());

handle date "2012-11-28T06:25:52.085Z"

new to java world.
so want a way to handle date 2012-11-28T06:25:52.085Z so that I can save this in oracle DB. wnat to save in column of type TIMESTAMP
Can someone pls help
Try this:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
Date date = df.parse("2012-11-28T06:25:52.085Z");
System.out.println(date);
After parsing the date string to get Date instance, you can store it into the database.
Try This.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
String sDate="2012-11-28T06:25:52.085Z";
Date tempDate = sdf.parse(sDate);
Timestamp dateInTimeStamp = new Timestamp(tempDate .getTime());
This will directly give your the TimeStamp Object.
Alternatively, use Joda-time for this purpose:
`DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z');
Timestamp forDatabase = new Timestamp(dateFormatter.parseDateTime(myString).toDate());`

how to convert datetime to timestamp in java

forum member
I am having one problem with date time in java. Actually I am receiving the startdate in format 2012-02-27T01:10:10 and I want to insert the received date to my database having datetime datatype.
Actually I tried to convert the startdate received to datetime by below code
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Date endD = sdf.format(eDate);
but with the above code only date gets added to my database like 2012-02-27 00:00:00
I want to add the time also to my database but when I change the SimpleDateFormat to SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); nothing works.
please suggest me some solution I can apply so my time also gets added to database. I am using Hibernate JPA as my persistence layer.
SimpleDateFormat's format() method doesn't return a Date type.
try this:
Date startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(sDate);
Try this,
yyyy-MM-dd'T'HH:mm:ss
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Timestamp startTime = new Timestamp(startD.getTime());
Date endD = sdf.format(eDate);
Timestamp endTime = new Timestamp(endD.getTime());
Of course only the date is parsed, since the pattern you provided to the SimpleDateFormat constructor only contains the date part! Add the time part to it and it will parse the time too just fine.
you can try like this....
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

Categories

Resources