I'm experimenting on a Java Program that makes use of Jasper Reports. What started out as a (supposedly) simple "arrange the dates in descending order" task for the Report became more complex when I found out that the 'dates' were in String format, and thus, were being sorted, albeit in a wrong manner. Example:
03/26/12
03/26/12
08/11/12
08/26/12
10/26/11
I can only guess that the 10/26/11 is placed on the bottom simply because of the 10 in front.
I've looked into the Jasper Report using iReport 3.0.0, and I've found the following:
The date in question (named: DTEEFFEC), under Fields, is set to String.
The textField is also set to String.
This doesn't produce any errors, it only makes it difficult, if not impossible, to arrange the 'dates' in descending order.
So I've done the following:
Left DTEEFFEC as is (String).
Changed the textField from Java.Lang.String to Java.Util.Date
Added the following to the New Field Expression:
new SimpleDateFormat("MM-dd-yyyy").parse($F{DTEEFFEC}.toString())
I found out that bit of code after some research on my problem. A lot of the responses were along the lines of "it worked", but not so for me.
Caused by: java.text.ParseException: Unparseable date: "03/26/2012"
That is what the Java program returns. I've tried tinkering with both the field and the textField (alternating between either String or Date values), but it gives me other errors entirely.
Can I have some help on this?
Thanks.
Other information: I'm using iReports 3.0.0 to modify the JRXML file, and Eclipse for the Java Program. If the Referenced Libraries under Eclipse is to be believed, I'm using JasperReports 3.5.2. The entire thing runs on Windows 7.
Look at your code:
new SimpleDateFormat("MM-dd-yyyy").parse(...)
That's clearly expecting something of the form "MM-dd-yyyy" such as "03-26-2012".
Now look at your actual data: "03/26/2012". (Apparently, even though your earlier samples were two-digit years...)
That's got slashes, not dashes. So you need to change your pattern appropriately:
new SimpleDateFormat("MM/dd/yyyy").parse(...)
Change the new SimpleDateFormat("MM-dd-yyyy") into new SimpleDateFormat("mm/dd/yyyy")
so the parser can correctly parse your date input
Related
I've tried coming up with a solution to this problem by combining a few separate issues other people posted on this site, but somehow can't get it right.
I receive a BigDecimal from the server which I need to display in a TextBox inside a GWT page.
BigDecimal bigDec = new BigDecimal(type.mb3.toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
t12.setText(bigDec.toString());
After this call the TextBox displays ex. 1200.00, which is the correct value, however I would like for it to be formatted with a German locale ##0,00.
I can't convert it by specifying the format via NumberFormat, as it doesn't accept BigDecimal. Is there another way I can format this without writing a neanderthal "if you see dot exchange it for comma" text parser?
The comment Thomas Broyer provided was the answer. I needed to use java.lang.Number instead of pure BigDecimal and it formatted correctly.
Recently I am being challenged by quite an "easy" problem. Suppose that there is sentences (saved in a String), and I need to find out if there is any date in this String. The challenges is that the date can be in a lot of different formats. Some examples are shown in the list:
June 12, 1956
London, 21st October 2014
13 October 1999
01/11/2003
Worth mentioning that these are contained in one string. So as an example it can be like:
String s = "This event took place on 13 October 1999.";
My question in this case would be how can I detect that there is a date in this string. My first approach was to search for the word "event", and then try to localize the date. But with more and more possible formats of the date this solution is not very beautiful. The second solution that I tried is to create a list for months and search. This had good results but still misses the cases when the date is expressed all in digits.
One solution which I have not tried till now is to design regular expressions and try to find a match in the string. Not sure how much this solution might decrease the performance.
What could be a good solution that I should probably consider? Did anybody face a similar problem before and what solutions did you find?
One thing is for sure that there are no time, so the only interesting part is the date.
Using the natty.joestelmach.com library
Natty is a natural language date parser written in Java. Given a date expression, natty will apply standard language recognition and translation techniques to produce a list of corresponding dates with optional parse and syntax information.
import com.joestelmach.natty.*;
List<Date> dates =new Parser().parse("Start date 11/30/2013 , end date Friday, Sept. 7, 2013").get(0).getDates();
System.out.println(dates.get(0));
System.out.println(dates.get(1));
//output:
//Sat Nov 30 11:14:30 BDT 2013
//Sat Sep 07 11:14:30 BDT 2013
You are after Named Entity Recognition. I'd start with Stanford NLP. The 7 class model includes date, but the online demo struggles and misses the "13". :(
Natty mentioned above gives a better answer.
If it's only one String you could use the Regular Expression as you mentioned. Having to find the different date format expressions. Here are some examples:
Regular Expressions - dates
In case it's a document or a big text, you will need a parser. You could use a Lexical analysis approach.
Depending on the project using an external library as mentioned in some answers might be a good idea. Sometimes it's not an option.
I've done this before with good precision and recall. You'll need GATE and its ANNIE plugin.
Use GATE UI tool to create a .GAPP file that will contain your
processing resources.
Use the .GAPP file to use the extracted Date
annotation set.
Step 2 can be done as follows:
Corpus corpus = Factory.newCorpus("Gate Corpus");
Document gateDoc = Factory.newDocument("This event took place on 13 October 1999.");
corpus.add(gateDoc);
File pluginsHome = Gate.getPluginsHome();
File ANNIEPlugin = new File(pluginsHome, "ANNIE");
File AnnieGapp = new File(ANNIEPlugin, "Test.gapp");
AnnieController =(CorpusController) PersistenceManager.loadObjectFromFile(AnnieGapp);
AnnieController.setCorpus(corpus);
AnnieController.execute();
Later you can see the extracted annotations like this:
AnnotationSetImpl ann = (AnnotationSetImpl) gateDoc.getAnnotations();
System.out.println("Found annotations of the following types: "+ gateDoc.getAnnotations().getAllTypes());
I'm sure you can do it easily with the inbuilt annotation set Date. It is also very enhancable.
To enhance the annotation set Date create a lenient annotation rule in JAPE say 'DateEnhanced' from inbuilt ANNIE annotation Date to include certain kinds of dates like "9/11" and use a Chaining of Java regex on R.H.S. of the 'DateEnhanced' annotations JAPE RULE, to filter some unwanted outputs (if any).
I'm trying to get date data types from an excel file, but the output when he's reading is 41306.038888888892.
This value just appear for date, is there any way to get the normal date?
I did not find anything searching in the web.
Hope someone can help
thanks
As with your previous question, I'd strongly suggest you try reading and understanding some of the various examples for this, you'll save yourself a lot of time! The two main ones probably being XSSFEventBasedExcelExtractor in Apache POI and XSSFExcelExtractorDecorator in Apache Tika
If you take the easy route, then you can just use XSSFSheetXMLHandler, which will handle all the pesky formatting stuff for you, and give you nicely formatted strings for your dates
Otherwise, if you want to stay at the low level, then you need to check the formatting rule applied to a cell. If it's a date-based format string, you then need to convert it from a number into a Date object. Handily, there's a POI class DateUtil which can both help you check if a cell is Date formatted, and convert it into a Java Date object for you
I have searched throughout the site but I think I have a slightly different issue and could really do with some help before I either have heart failure or burn the computer.
I dynamically generate a list of month names (in the form June 2011, July 2011) and obviously I want this to be locale sensitive: hence I use the simple date format object as follows:
//the actual locale name is dependent on UI selection
Locale localeObject=new Locale("pl");
// intended to return full month name - in local language.
DateFormat dtFormat = new SimpleDateFormat("MMMM yyyy",localeObject);
//this bit just sets up a calendar (used for other bits but here to illustrate the issue
String systemTimeZoneName = "GMT";
TimeZone systemTimeZone=TimeZone.getTimeZone(systemTimeZoneName);
Calendar mCal = new GregorianCalendar(systemTimeZone); //"gmt" time
mCal.getTime(); //current date and time
but if I do this:
String value=dtFormat.format(mCal.getTime());
this "should" return the localized version of the month name. In polish the word "September" is "Wrzesień" -- note the accent on the n. However all I get back is "Wrzesie?"
What am I doing wrong?
Thanks to all - I accept now that it's a presentation issue - but how can I "read" the result from dtFormat safely - I added some comments below ref using getBytes etc. - this worked in other situations, I just can't seem to get access to the string result without messing it up
-- FINAL Edit; for anyone that comes accross this issue
The answer was on BalusC's blog : http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html#DevelopmentEnvironment
Basically the DTformat object was returning UTF-8 and was being automatically transformed back to the system default character set when I read it into a string
so this code worked for me
new String(dtFormat.format(mCal.getTime()).getBytes("UTF-8"),"ISO-8859-1");
thank you very much for the assistance
Your problem has nothing to do with SimpleDateFormat - you're just doing the wrong thing with the result.
You haven't told us what you're doing with the string afterwards - how you're displaying it in the UI - but that's the problem. You can see that it's fetching a localized string; it's only the display of the accented character which is causing a problem. You would see exactly the same thing if you had a string constant in there containing the same accented character.
I suggest you check all the encodings used throughout your app if it's a web app, or check the font you're displaying the string in if it's a console or Swing app.
If you examine the string in the debugger I'm sure you'll see it's got exactly the right characters - it's just how they're getting to the user which is the problem.
In my tests, dtFormat.format(mCal.getTime()) returns
październik 2011
new SimpleDateFormat(0,0,localeObject).format(mCal.getTime()) returns:
poniedziałek, 3 październik 2011 14:26:53 EDT
I'm trying to find a complete tutorial about formatting strings in java.
I need to create a receipt, like this:
HEADER IN MIDDLE
''''''''''''''''''''''''''''''
Item1 Price
Item2 x 5 Price
Item3 that has a very
long name.... Price
''''''''''''''''''''''''''''''
Netprice: xxx
Grossprice: xxx
VAT: xxx
Shipping cost: xxx
Total: xxx
''''''''''''''''''''''''''''''
FOOTER IN MIDDLE
The format to pass to string.format is documented here:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
From the page:
The format specifiers for general,
character, and numeric types have the
following syntax:
%[argument_index$][flags][width][.precision]conversion
The optional argument_index is a
decimal integer indicating the
position of the argument in the
argument list. The first argument is
referenced by "1$", the second by
"2$", etc.
The optional flags is a set of
characters that modify the output
format. The set of valid flags depends
on the conversion.
The optional width is a non-negative
decimal integer indicating the minimum
number of characters to be written to
the output.
The optional precision is a
non-negative decimal integer usually
used to restrict the number of
characters. The specific behavior
depends on the conversion.
The required conversion is a character
indicating how the argument should be
formatted. The set of valid
conversions for a given argument
depends on the argument's data type.
formating string is some what complicated, for this kind of requirement.
so its better to go for some reporting tool using the format you have given.
which would be the better approach.
Either a crystal report or some others which are easy to implement.
Trying to do this with formatting a string will cost you to much time and nerves. I would suggest a templating engine like Stringtemplate or something similar.
with doing these you will separate the presentation from the data and that will be a very good thing in the long run.
See if these classes in java.text package can help..
Format
MessageFormat
Yea as solairaja said if you are planning to create reports or receipts you can go for reporting tools as Crystal reports
Crystal Report Crystal Report Tutorial
Or if you plan to use StringFormatting itself then "StringBuffer" would be the best option coz u can play around with it.
You should probably look at Java templating tools for this sort of multi-line reporting formatting.
Velocity is simple and forgiving of errors. Freemarker is very powerful but more intolerant. I would perhaps look at Velocity initially, and if you have to do more of this sort of work, take a further look at Freemarker.
Looks like the general advice from the community as a better approach to solve your problem is using a reporting tool.
Here you have a detailed list of open source Java charting and reporting tools:
http://java-source.net/open-source/charting-and-reporting
The most well known is, in my opinion, Jasper Reports. A lot of resources about it are available on the web