In mongodb adhoc query, before executing the query, how to format the date type element to dd\mm\yyyy format and then execute the query?
I solved this by inserting the datetime as integer using the getTime() method in java.
EG:
Date dt=new Date();
long integer_date=dt.getTime();
I used the above line of code to insert date as integer.With this it was easy to fetch records between a particular date.
I asked a similar question a little while back...this might be what you're looking for: What is the syntax for Dates in MongoDB running on MongoLab?
If you are using Java, you can create Date objects from strings using the parse method of the DateFormat class.
The Java documentation on the DateFormat Class may be found here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
The specific section on the parse method is here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html#parse%28java.lang.String%29
The Java documentation on the Date object may be found here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
As per the "Constructor Summary" section, the ability to pass a string into the constructor is "Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s)."
While I was researching the above, I also came across the Calendar class, which may be used for converting a Date object and a set of integers. It may not be necessary for this application, but I thought it might be useful to include a link to the documentation:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
Integers for year, month, day, hour, etcetera may be passed in via the set method:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set%28int,%20int,%20int,%20int,%20int%29
By way of example, here is a short Java Program that creates a number of Date objects, stores them in a Mongo collection, and then executes a query similar to what you have described. Hopefully it will help you to accomplish your goal. NOTE: This program drops a collection named "dates", so be sure to change the collection name if you already have such a collection in your database!
public static void main(String[] args) throws UnknownHostException, MongoException {
Mongo m = new Mongo( "localhost:27017" );
DB db = m.getDB("test");
DBCollection coll = db.getCollection("dates");
coll.drop();
DateFormat df = DateFormat.getInstance();
String dateString = new String();
Date myDate = new Date();
// Save some test documents
for(int i=1; i<11; i++){
dateString = "04/" + String.valueOf(i) + "/12 11:00 AM, EST";
BasicDBObject myObj = new BasicDBObject("_id", i);
try {
myDate = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
myObj.put("date", myDate);
System.out.println(myDate);
coll.save(myObj);
}
// Build the query
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = df.parse("04/4/12 11:00 AM, EST");
endDate = df.parse("04/6/12 11:00 AM, EST");
} catch (ParseException e) {
e.printStackTrace();
}
BasicDBObject dateQuery = new BasicDBObject();
dateQuery.put("$gte", startDate);
dateQuery.put("$lte", endDate);
System.out.println("---------------");
//Execute the query
DBCursor myCursor = coll.find(new BasicDBObject("date", dateQuery));
//Print the results
while(myCursor.hasNext()){
System.out.println(myCursor.next().toString());
}
}
This is use full to format code to date format from simple date time format and the reverse steps also supporting this way to retrieve date from MongoDB.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fDate = formatter.parse((String) metaData.getValue());
newMeta.setValue(fDate);[![In this image you can see how is the save scenario process in mongoDB][1]][1]
Date class has a before(date) or after(date) method... It is easy to use: no conversion to seconds/milliseconds.
public void execute(Tuple input) {
try {
date=(Date) input.getValueByField("date");
boolean before = date.before(myDate); // compare the data retrieved with your date.
if (before) {
...
} else {
...
}
} catch (Exception e) {
logger.error("Error...", e);
}
This approach is easier than the accepted answer..
Related
I'm fixing a bug in JAVA/Angular Project, I'm getting a Date in Millisecodes from the front End, then I change the date from Millisecondes to "yyyy MM dd HH:mm:ss" format using SimpleDateFormat class in JAVA.
I want to compare the date that I'm getting from the front end with a field in a Table in my DataBase using criteriaBuilder.greaterThan().
The type of the field is bigInit(20).
I proposed as a solution to compare the dates using TimesTamp type, but the request from the client is a comparaison using Date in JAVA
public Specification<T> greater(Object value, String field, String type) {
return (root, criteriaQuery, criteriaBuilder) -> {
Path tuple = getPath(root, field);
System.out.println("type" + tuple.getJavaType());
if (tuple.getJavaType().isAssignableFrom(Date.class)) {
return criteriaBuilder.greaterThan(tuple, convertFilterDateToDate(value.toString()));
}
return criteriaBuilder.greaterThan(getPath(root,field),Double.valueOf(value.toString()));
};
}
This method takes 3 parametrs :
Object value : its type is Long in my case, it is the value of the date taken from the front End, I wrote a method to convert the value from Long to Date using SimpleDateFormat.
String field: its the field in my table, it contains dates with type Long.
String Type: it contains the value 'endDate' in my case.
Below, the definition of getPath Method :
public Path getPath(Root<T> root, String field){
String fiedls[] = field.split("\\.");
if(!field.contains(".")){
System.out.print(root.get(field));
return root.get(field);
}
else if (fiedls.length==2){
Join<Operation,Object> join = root.join(fiedls[0]);
return join.get(fiedls[1]);
}
else if(fiedls.length==3){
Join<Operation,Object> join = root.join(fiedls[0]);
Join<Object,Object> join1 = join.join(fiedls[1]);
return join1.get(fiedls[2]);
}
return null;
}
The request is to compare date using Date type in java and criteriaBuilder.greaterThan() , any Idea ?
I have to made a Query in executeQuery , and I have to filter by date field,
my code is :
public void executeQuery()
{
utcDateTime dateUTC, datenullUTC;
query q = new Query();
QueryBuildRange qbr;
QueryBuildDataSource qbds ;
QueryRun queryRun;
dateUTC = DateTimeUtil::newDateTime(_dateValue, 0, DateTimeUtil::getCompanyTimeZone());
qbds = q.addDataSource(tableNum(MCRCustCategory) );
qbds.addRange(fieldNum(MCRCustCategory, ValidTo)).value(strFmt ("> %1", dateUTC) );
queryRun = new QueryRun (q);
super();
}
In my init I call the executeQuery, but don't filter in my Form.
How to use the date in the Range ?
Thanks all,
enjoy!
You use a table which use date effective. You assume you have to do the selection yourself, this is not true.
Use this instead:
public void executeQuery()
{
this.queryBuildDataSource().validTimeStateAsOfDate(_dateValue);
super();
}
If you have an interval, use this instead:
this.queryBuildDataSource().validTimeStateDateRange(fromDate, toDate)
Your code as provided in the question does not do anything at all, as the form does not use the query you build. You buildt the wrong query anyway!
This blog post explains it concisely.
I have a column of date type (daterecord) in PostgreSql and jdatechooser component in java (dateChooser). I am trying to insert the selected date into my database with this initial code:
Date daterec = dateChooser.getDate();
String sql= "INSERT INTO date values (?)";
pst.prepareStatement(sql);
pst.setDate(1, daterec);
pst.execute();
..but I know my setDate code is wrong..please help what to do?
i can tell you how to insert a date record into a mysql table by using the Datechooser control..it is how i do it..so it may differ from your point of view
public void getdate() {
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String s=df.format(jDateChooser1.getDate());
jLabel1.setText(""+s);
}
public void insert(){
try{
Class.forName("java.sql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/<database_name>","root","<db password>");
Statement stmt=con.createStatement();
String query="insert into test values('"+jLabel1.getText()+"')";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Insert successful");
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"Error in connectivity");
}
}
This the code. I have mentioned where the query stops. There is no error in the console too. What could be the problem. I am using postgres database. getting data from jsp servlet and passing to dao through servlet as string. But as my db has different format i want to convert the variables to their respective types. But i first want to check whether insert query works with dummy data. It seems that every thing is working fine but code flow stops where mentioned and there is no data inserted in my db also.
public void doInsert(Connection conn, String i, String nam,String indate, String amont, String tx, String tot,String closd, String shipvia, String not) throws Exception {
ResultSet rs = null;
ResultSet rs1 = null;
Statement st=null;
Statement st1=null;
// TODO Auto-generated method stub
try{
/* String in=indate;
String reverse = new StringBuffer(in).reverse().toString();
System.out.println(reverse);
System.out.println(reverse);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
String dateInString = indate;
Date date = sdf.parse(dateInString);
System.out.println(date);*/
/*String it=i;
String n=nam;
String in=indate;
String a=amont;
String t=tx;
String tota=tot;
String closed=closd;
String ship_via=shipvia;
String note=not;
to_date("+date+",'YYYY-MM-DD')*/
System.out.println("came above sql");
/*to_date("+date+",'YYYY-MM-DD')*/
String sql="insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values(100001,to_date('1963-09-01', 'YYYY-MM-DD'),100001,100.00,20.00,120.00,TRUE,'tnt','note 1')";
//"insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values('',to_date('1963-09-01', 'YYYY-MM-DD'),"+i+","+amont+","+tx+","+tot+","+closd+","+shipvia+","+not+")";
System.out.println("after 1st query");
String sql1="insert into clients(client_id,name) values("+i+","+nam+")";
System.out.println("after 2nd query");
st =conn.createStatement();
st1 =conn.createStatement();
//Statement stmt1 = conn.createStatement();//connection to statement
System.out.println("above execute"); //<======= code stops here
rs=st.executeQuery(sql);
System.out.println("above execute1");
rs1=st1.executeQuery(sql1);
System.out.println("inserted dao");
}catch(Exception e){
e.printStackTrace();
throw e;
}
// TODO Auto-generated method stub
}
Please help me. what could be the reason?
I'm using Entity Framework 4.3. In my SQL Server 2008 db, I have some dates stored as dates rather than datetime.
I need to retrieve data using the date field, here a test code sample:
public static Applicant Create()
{
var dt = new DateTime(1967, 08, 03);
var r = new CrudRepo<Applicant>(UowHelper.GetUow().Context);
return r.Find(a => a.DateOfBirth == dt).Single();
}
However, I'm getting an issue with 'missing sequence'.
Any ideas as to how I get around this?
I'll also need to update the database too at some point.
Thanks.
The actual result of var dt = new DateTime(1967, 08, 03); is 8/3/1967 12:00:00 AM
The DataType of the DateOfBirth is Date so we need to TruncateTime the time.
msdn: EntityFunctions.TruncateTime Method
public static Applicant Create()
{
var dt = new DateTime(1967, 08, 03);
var r = new CrudRepo<Applicant>(UowHelper.GetUow().Context);
return r.FirstOrDefault(a => a.DateOfBirth == EntityFunctions.TruncateTime(dt));
}
or remove the .Single() method instead use the .FirstOrDefault() Method
FYI, to add to spajce's answer,
System.Data.Entity.Core.Objects.EntityFunctions
has been deprecated to
System.Data.Entity.DbFunctions