XPath Filter by Date - java

I need to filter the records by date through JAVA class:
public static final String DATE_TIME = "DateTime"
Date dateNow = setTimeToZero(Calendar.getInstance().getTime());
String date = DATE_TIME_FORMAT.format(dateNow);
Request request = table.createRequest();
DATE_FILTER = XPathFilter.newFilter("date-greater-than(" + Root_Table_DateField.format() + '$date')");
request.setXPathFilter(DATE_FILTER);
request.setXPathParameter(DATE_TIME, date);
RequestResult = reqResult = request.execute();
The field I am trying to access is define as DateTime, but I don't want the time now, so I set the time to zero, so I can filter for all field with date greater than dd-MM-yyyT00:00:00:000
But it return a predicate error: PredicateException: Invalid XPath expresion ./dateTime = 26-06-2020T00:00:00:000 - Unexpected 'T00:00:00.000'
Any clue?
Thank you

Try to add the date formatted like that (xs:date("2020-06-26Z")
date-greater-than(xs:date("2004-12-25-12:00"), (xs:date("2020-06-26Z"))
Reference: https://www.w3.org/TR/xpath-functions-31/

Related

How to solve this error "String Cannot be converted to Date"?

Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.

Biweekly/google-rfc-2445 RRule different behaviour based on start date

Different behaviour of RRULE based on start time :
Hi, I am currently trying to write a cron to rrule convertor and encountered some issues with some particular rules.
For the following rule :
"FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0"
The behaviour of the dates iterator iss different depending on what the start time specified is :
final String rule2 = "FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0";
final Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse("2019-10-01");
final Date startDate2 = new SimpleDateFormat("yyyy-MM-dd").parse("2019-12-01");
System.out.println("Biweekly Rule Date 1");
final List<Date> biweeklyStartDate1 = biweeklyDates(rule2, startDate, 100);
System.out.println("Biweekly Rule Date 1 Result Count " + biweeklyStartDate1.size());
System.out.println("Biweekly Rule Date 2");
final List<Date> biweeklyStartDate2 = biweeklyDates(rule2, startDate2, 100);
System.out.println("Biweekly Rule Date 2 Result Count " + biweeklyStartDate2.size());
private static List<Date> biweeklyDates(final String rule, final Date date, final int limit) {
final RecurrenceRuleScribe scribe = new RecurrenceRuleScribe();
final ParseContext context = new ParseContext();
context.setVersion(ICalVersion.V2_0);
final RecurrenceRule recurrenceRule = scribe.parseText("RRULE:" + rule,null, new ICalParameters(), context);
final DateIterator iterator = recurrenceRule.getDateIterator(date, TimeZone.getTimeZone("GMT"));
final List<Date> values = new ArrayList<>();
while (iterator.hasNext()) {
final Date next = iterator.next();
values.add(next);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(next));
if (values.size() >= limit) {
break;
}
}
return values;
}
In this example I try to retrieve a 100 occurences using the same rule. The occurences returned differ based on start time specified.
The first date would return the expected 100 results, the second one would return a single invalid occurence, which seem to be the start date.
It seems to be caused by last month of the year, whn specifying another date with December, the same return seems to be returned.
Google-rfc-2445 has the same behaviour but ical4j and some other rrule evaluators from other languages were able to produce the expected results.

How do I convert Google's DateTime object to a long-type value?

I am trying to integrate a database with a web application that extracts event data from Google Calendar API which inputs the data into the database. The following code is identical to the Quickstart class provided by Google.
I basically want 'DateTime start' to be converted to 'long start'. I need the long value for SQL.
import com.google.api.client.util.DateTime;
// ...
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list(calendarId)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
DateTime end = event.getEnd().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s\n", start.toString());
Google has implemented the Rfc3339 parser in Google HTTP Client Library. You can try parsing it first and the use the DateTime.getValue() function to convert it into long.
You may also try using the DatetimeFormatter to format it to the way you want the value.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.of("UTC"));
public void convertDatetime() {
String timeStamp = "2019-05-24T11:32:26.553955473Z";
DateTime dateTime = DateTime.parseRfc3339(timeStamp);
long millis = dateTime.getValue();
String result = formatter.format(new Date(millis).toInstant());

Azure DocumentDB - How can I fetch documents from the collection of particular date?

Each document contains date property shows when it is stored, so how can I fetch data stored on particular date or between two dates. What is the best way to do this. My implementation is based on Java. Thanks in advance.
I don't have the Java code, but you'll have to set up your collection to use Range indexing on the DateTime strings, then you'll be able to query for dates within a certain time range. The .NET code is to set up range indexing is:
DocumentCollection collection = new DocumentCollection { Id = "orders" };
collection.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
await client.CreateDocumentCollectionAsync("/dbs/orderdb", collection);
See https://learn.microsoft.com/en-us/azure/documentdb/documentdb-working-with-dates#indexing-datetimes-for-range-queries and search for Range on this page https://learn.microsoft.com/en-us/azure/documentdb/documentdb-indexing-policies.
Just using Azure DocumentDB SDK for Java to query documents by _ts property. The document _ts property is as below.
_ts: This is a system generated property. It specifies the last updated timestamp of the resource. The value is a timestamp.
Here is my sample code as below. The _ts unit is second.
// Initialize a DocumentDb client.
String serviceEndpoint = "https://<your-documentdb-name>.documents.azure.com:443/";
String masterKey = "<your-documentdb-key>";
DocumentClient client = new DocumentClient(serviceEndpoint, masterKey, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
// Get a collection link via collection id.
String collId = "<collection-Id>";
String query = String.format("SELECT * from ROOT r WHERE r.id = '%s'", dcId);
FeedOptions options = null;
List<DocumentCollection> dcs = client.queryCollections(dbLink, query, options).getQueryIterable().toList();
String collLink = dcs.size() >0 ? dcs.get(0).getSelfLink() : null;
// Generate a query string, see below.
.......
client.queryDocuments(collection.getSelfLink(), query, null);
A query string for fetching data stored on particular date:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = "2017-03-01";
long timestamp = sdf.parse(dateStr).getTime()/1000;
String query = String.format("select * from c where c._ts = %d", timestamp);
A query string for fetching data stored between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = "2017-03-01";
String endDateStr = "2017-03-31";
long tsStart = sdf.parse(startDateStr).getTime()/1000;
long tsEnd = sdf.parse(endDateStr).getTime()/1000;
String query = String.format("select * from c where c._ts >= %d and c._ts <= %d", tsStart, tsEnd);

How do i handle an empty jXDatePicker?

I have a swing form which includes jXDatePicker to capture dates. When a date is not selected in the jXDatePicker an error is thrown when the trying to inserting the date into the database. Below is the error I am getting in Netbeans:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
Below is the code that is giving me errors:
String dateOpened, dateOfLastUpdate, dateOf1stDelinquency, dateOfLastPayment, dateClosed;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOpened = format.format(jXDatePicker7.getDate());
dateOfLastUpdate = format.format(jXDatePicker2.getDate());
dateOf1stDelinquency = format.format(jXDatePicker4.getDate());
dateOfLastPayment = format.format(jXDatePicker5.getDate());
dateClosed = format.format(jXDatePicker6.getDate());
String query2 = "insert into ACCOUNT (ACCOUNT_NUMBER,DATE_CLOSED ,DELINQUENCY_DATE, UPDATE_DATE,AMOUNT_OWING,"
+ "BALANCE,PAYMENT_HISTORY,ACCOUNT_STATUS,MONTHLY_PAYMENT,TERMS_DURATION,PRINCIPAL,CREDIT_LIMIT,"
+ "DATE_OPENED,PORTIFOLIO_TYPE,ACCOUNT_TYPE,NATIONAL_ID,COSIGNER_NATIONAL_ID)"
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement2 = con.prepareStatement(query2);
preparedStatement2.setString(1, acc_no);
preparedStatement2.setString(2, dateClosed);
preparedStatement2.setString(3, dateOf1stDelinquency);
preparedStatement2.setString(4, dateOfLastUpdate);
preparedStatement2.setDouble(5, amount_owing);
preparedStatement2.setDouble(6, current_balance);
preparedStatement2.setString(7, payment_history);
preparedStatement2.setString(8, account_status);
preparedStatement2.setDouble(9, monthly_payment);
preparedStatement2.setDouble(10, terms_duration);
preparedStatement2.setDouble(11, principal);
preparedStatement2.setDouble(12, credit_limit);
preparedStatement2.setString(13, dateOpened);
preparedStatement2.setString(14, portfolio_type);
preparedStatement2.setString(15, acc_type);
preparedStatement2.setString(16, national_id);
preparedStatement2.setString(17, cosigner_national_id);
preparedStatement2.executeUpdate();
Some dates are not required and applicable on some instances, therefore the user cannot select a date under such circumstances.
Check each individual JXDatePicker's date like jXDatePicker2.getDate() for null. Do not call format.format if that date does happen to be null. I get that exact same error you mentioned on the format.format line if the date is empty and enter is pushed. Instead, go for some default time, like new Date(0); meaning:
format.format(new Date(0));
Use following code and make sure that dateOpened column in database accept NULL values.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
dateOpened = null;
}
If you don't want to insert NULL value then show error message as
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
//error
}

Categories

Resources