Java.util.DateFormat / SimpleDateFormat
Hi to All,
It would be kind to let me know how could i resolve this problem .
The user enters an expiry date as MM/dd/yyyy i.e 07/14/2002.
This date I would like to store in the database in the following format:
MM/dd/yyyy i.e '07/14/02 3:41:31 PM'
I am able to store '7/14/02' but not the hour,minute,second and AM/PM part. How can i do so ?
I have done it in this way :-
String sExpiryDate = "07/14/2003";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
/* tried adding 'hh:mm:ss' to the above line , but i got ParseException */
java.util.Date dExpiryDate = formatter.parse(sExpiryDate);
long lexp_date = dExpiryDate.getTime();
java.util.Date dExpireDate = new java.util.Date(lexp_date);
This sExpireDate when printed comes as " Mon Jul 14 00:00:00 BST 2003 "
How could i also add hour, minute and seconds to this expiry date?
Any response will be appreciated.
Thanks
Regards,
John
Check out the javadoc for SimpleDateFormat. It will show you the way you can get the fields your missing
http://java.sun.com/j2se/1.4/docs/api/java/text/SimpleDateFormat.html
Similar Messages
-
Java.util.text.SimpleDateFormat.parse strange behavior
Wow !
if I parse "10/14/2002" I get "0/2/2003", that is, the month 14 is considered 12 (december) + 2 additional months and therefore february in the next year!!
any idea ?
Paolo Denti
=============================
public class Test {
public static void main(String[] args) {
java.util.Date testDate = null;
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd-MM-yyyy");
try {
testDate = formatter.parse("10-14-2002");
catch (java.text.ParseException e) {
System.out.println("Data scassata: " + e.getMessage());
System.exit(1);
System.out.println(testDate.toString());
=================================
prints "Mon Feb 10 00:00:00 CET 2003"Tryformatter.setLenient(false);if you do not want this behaviour.
-
DateFormat in java.util.logging logging.properties - Please help
Hello
I have problem with properties file for my logger.
Everything is ok except one thing: the date format.
The question is how to say in my application.logging.properties, that the dates should be formated in particular way?
In log4j it was (is) possible in way like this:
log4j.appender.R.layout.ConversionPattern=$d{dd-MM-yyyy hh:mm:ss,SSS} %p [%t] %c - %m%nwhen I use java.util.logging I always get the dates in form like this:
Jan 8, 2004 1:09:42 PMThe question is how to set date format pattern to for example: dd-MM-yyyy hh:mm:ss,SSS using properties file, to have the date in form like this:
08-01-2004 13:09:42,768Thank You very much.
MaciekHi,
did you find out how to do this?
I'm after the exact same thing. -
Converting Java.util date to XML date in format YYYY-MMM-dd
I'm using below code to convert java.util.date to XML date
public static XMLGregorianCalendar toXMLDate(Date dte) {
try {
// this may throw DatatypeConfigurationException
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
GregorianCalendar calendar = new GregorianCalendar();
// reset all fields
calendar.clear();
Calendar parsedCalendar = Calendar.getInstance();
parsedCalendar.setTime(dte);
calendar.set( parsedCalendar.get(Calendar.YEAR ),
parsedCalendar.get(Calendar.MONTH),
parsedCalendar.get(Calendar.DATE ));
XMLGregorianCalendar xmlCalendar = datatypeFactory.newXMLGregorianCalendar( calendar );
xmlCalendar.setTimezone( DatatypeConstants.FIELD_UNDEFINED );
xmlCalendar.setFractionalSecond( null );
return xmlCalendar;
I need to get the date in the format YYYY-MMM-dd, but it returns in a format YYYY-MM-dd. Can anyone tell me how can i change the format? Thanks>
The snippet of ApplicationClient where the assignment took place and the syntax occurred were:
1. DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
2. DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
3. Date date = new Date();
4. CustomerDetail customerDetail = new CustomerDetail();
5. customerDetail.setCollectionDate(dateFormat.format(date)); //got the above syntax error
6. customerDetail.setCollectionTime(timeFormat.format(date)); //got the above syntax error
.....I am running JDK 1.6.0_10, Glassfish v2r2, MySQL 5.0, Netbeans 6.1 on Windows XP platform.The format method returns a String not a Date. Why not just store the Date as is without formatting, and format it when you want to retrieve it from the DB and display it?
m -
Hi all,
How to change a date value from "java.util.Date" to "java.sql.Date"?
I m still confusing what's the difference between them.....
thanks
Regards,
KinThanks
but my sql statement can only accept the format (yyyy-MM-dd)
such as "select * from xx where somedate = '2004-12-31'
but when i show it to screen, i want to show it as dd-MM-yyyy
I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
public String date2str(java.util.Date thisdate) {
if (thisdate != null) {
java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
return date2str(thissDate);
} else {
return "";
public String date2str(java.sql.Date thisdate) {
if (thisdate != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(thisdate);
} else {
return "";
public java.util.Date str2date(String thisdate) {
String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
java.util.Date returndate = null;
if (thisdate != null) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
try {
returndate = dateFormatter.parse(thisdate);
} catch (ParseException pe) {
System.out.println (pe.getMessage());
return returndate;
} -
Cannot convert from java.util.Date to java.sql.Date
In the below code am trying to get the current date and 60 days prior date:
Date todayDate;
Date Sixtydaysprior;
String DATE_FORMAT = "MM/dd/yy";
DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = sdf.parse(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -60);
Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
<%@page
import="java.util.Calendar,
java.text.SimpleDateFormat,
java.text.ParseException,
java.util.*"
%>Shows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
Thanks.
Edited by: MiltonDetroja on May 22, 2009 11:03 AMShows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
java.util.Date today = new java.util.Date();
long t = today.getTime();
java.sql.Date dt = new java.sql.Date(t); -
Java.util.Calendar returning wrong Date object
Example: This was my scenario last night. A server in California has date/time of 'Mon Aug 18'. Current time in Indiana is 'Sun Aug 17'. I use Calendar.getInstance(TimeZone.getTimeZone("America/Indiana/Indianapolis")) to return a Calendar instance. I then call the getTime() method on that instance. It should return a Date object relating to that particular time zone. It will not. It defaults back to the server time. When I print out the Calendar instance everything is good, correct date, correct time,etc. WHY WON'T THE getTime() return the correct java.util.Date???
Following is the output was run today so the dates happened to be the same so focus on the Time. Output includes Server time, new Calendar values, and the Date returned by calendar instance getTime(). See that the Calendar is getting the correct Time.
SERVER DATE=Mon Aug 18 15:52:13 CEST 2003
CALENDAR INSTANCE=java.util.GregorianCalendar[time=1061214732975,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Indiana/Indianapolis",offset=-18000000,dstSavings=0,useDaylight=false,transitions=35,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2003,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=230,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=52,SECOND=12,MILLISECOND=975,ZONE_OFFSET=-18000000,DST_OFFSET=0]
Date from getTime()=Mon Aug 18 15:52:12 CEST 2003I got it worked with using DateFormat.parse !
The trick is to instantiate a new Date object as a result
of parsing out of 'localized' date string.
with below code :
Calendar localCal = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
localCal.set(Calendar.DATE, 25);
localCal.set(Calendar.MONTH, 7);
localCal.set(Calendar.YEAR, 2003);
localCal.set(Calendar.HOUR_OF_DAY,6);
localCal.set(Calendar.MINUTE, 38);
localCal.set(Calendar.SECOND, 11);
Calendar sinCal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
sinCal.setTimeInMillis(localCal.getTimeInMillis());
int date = sinCal.get(Calendar.DATE);
int month = sinCal.get(Calendar.MONTH);
int year = sinCal.get(Calendar.YEAR);
int hour = sinCal.get(Calendar.HOUR_OF_DAY);
int min = sinCal.get(Calendar.MINUTE);
int sec = sinCal.get(Calendar.SECOND);
String sinTimeString = date + "/" + month + "/" + year + " " + hour + ":" + min + ":" + sec;
System.out.println("VIDSUtil.hostToLocalTime : time string now in SIN time : " + sinTimeString);
java.util.Date sinTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(sinTimeString);
System.out.println("time in SIN using Date.toString(): " + sinTime.toString());
It prints out :
VIDSUtil.hostToLocalTime : time string now in SIN time : 25/7/2003 21:38:11
time in SIN using Date.toString(): Fri Jul 25 21:38:11 PDT 2003
(Ignore the PDT, because Date.toString() defaults where the JVM is running) -
Can't create log file with java.util.logging
Hi,
I have created a class to create a log file with java.util.logging
This class works correctly as standalone (without jdev/weblogic)
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class LogDemo
private static final Logger logger = Logger.getLogger( "Logging" );
public static void main( String[] args ) throws IOException
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + "SEC" + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
//fh.setFormatter(new XMLFormatter());
fh.setFormatter(new SimpleFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
// force a bug
((Object)null).toString();
catch (IOException e)
logger.log( Level.WARNING, e.getMessage(), e );
catch (Exception e)
logger.log( Level.WARNING, "Exception", e);
}But when I use this class...
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class TraceUtils
public static Logger logger = Logger.getLogger("log");
public static void initLogger(String ApplicationName) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + ApplicationName + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
fh.setFormatter(new XMLFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
catch (IOException e)
System.out.println(e.getMessage());
}and I call it in a backingBean, I have the message in console but the log file is not created.
TraceUtils.initLogger("SEC");why?
Thanks for your help.I have uncommented this line in logging.properties and it works.
# To also add the FileHandler, use the following line instead.
handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
jdev ignore the parameters of the FileHandler method .
And it creates a general log file with anothers log files created each time I call the method logp.
So I play with these parameters
fh = new FileHandler(logFileName,true);
fh = new FileHandler(logFileName,0,1,true);
fh = new FileHandler(logFileName,10000000,1,true);without succes.
I want only one log file, how to do that? -
A way to increment java.util.Date
hi folks,
does anyone know of a clean way to increase java.uil.Date object by one day? I can use setTime(getTime()+1_day_time_in_millsecons); but it seems unnatural...
thanksLike below
cal.add(cal.DATE,num); /* Date Offset */
/* DateOffset.java
2003/01/15 eric.leung
Compile
=======
javac DateOffset.java
Application
===========
java DateOffset -d off_set
Return
======
yyyy/mm/dd
import java.util.*;
import java.text.*;
public final class DateOffset {
public static void main(String[] args)
throws Exception{
int num = 0;
int i = 0;
for (int j=0;j< args.length;j++) {
if (args[j].trim().equals("-d")) {
if ( j + 1 < args.length ) {
try {
num = Integer.parseInt(args[j+1]);
} catch (NumberFormatException e) {
num = 0;
TimeZone zone = new SimpleTimeZone(8*60*60*1000,"GMT+0800");
Calendar cal = Calendar.getInstance(zone);// this seems to be a point
cal.set(Calendar.YEAR, 1970); // example
DateFormat formatter = new SimpleDateFormat();
formatter.setCalendar(cal); //this is necessary
Date date = new Date();
formatter.format(date);
cal.add(cal.DATE,num); /* Date Offset */
System.out.print(cal.get(cal.YEAR) +"/");
i = cal.get(cal.MONTH) + 1;
if (cal.get(cal.MONTH) < 10 )
System.out.print("0" + i + "/");
else
System.out.print(i + "/");
if (cal.get(cal.DATE) < 10 )
System.out.println("0" + cal.get(cal.DATE));
else
System.out.println(cal.get(cal.DATE));
} -
Java.util.Calendar calculates wrong date when any duration is added
Hi friends,
I am trying to calculate the date through java.util.Calendar object and getting wrong value. Let me explain the scenario -
Scenario1:
I have taken start date and added some duration to that and expecting a new date which should be calculated as (start date+ duration). The value is as below -
start date = 2012-01-09 (9 January 2012 )
duration = 1year, 1month, 20 days
new date = 2013-02-28 ( 28 February 2013)
*Here new date I am expecting is 2013-03-01 (1 March 2013).
Scenario2:
I have taken another set of values as below -
start date = 2011-02-15 (15 February 2011)
duration = 1year, 1month, 15days
new date = 2012-03-30 (30 March 2012)
*Here new date is as expected.
Scenario1 data is giving me wrong result. Please let me know if any more information is required. Any help will be appriciated. Thanks in advance.
Edited by: user560316 on ९ जनवरी, २०१२ ६:२३ अपराह्न
Edited by: user560316 on ९ जनवरी, २०१२ ६:२४ अपराह्नIt all looks pretty straightforward to me. Try running the following code:
public class TestCalendar {
public static void main(String[] args) {
java.util.Calendar myDate = java.util.Calendar.getInstance();
java.text.DateFormat df = new java.text.SimpleDateFormat("dd MMMM yyyy");
myDate.set(2012, java.util.Calendar.JANUARY, 9);
System.out.println("Start date = " + df.format(myDate.getTime()));
myDate.add(java.util.Calendar.YEAR, 1);
myDate.add(java.util.Calendar.MONTH, 1);
myDate.add(java.util.Calendar.DAY_OF_MONTH, 20);
System.out.println("End date = " + df.format(myDate.getTime()));
}This gives the following result:
Start date = 09 January 2012
End date = 01 March 2013 -
Default java.util.Date Patter
Hello,
I tried to parse the default Date output String java.util.Date.toString()
"Fri Jan 01 00:00:00 CET 2049" But this patter don't work "E MMM dd HH:mm:ss Z" can anybody tell me what patter the Date Object use? In the API I found no informationen.
String body = "Fri Jan 01 00:00:00 CET 2049";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z");
Date date = (Date)formatter.parse(body);Thanks for helpYou can use SimpleDateFormat API for that. You should use the format() method instead of parse() method.
Date today = new Date();
String humanReadableDateFormat = new SimpleDateFormat("yyyy/MM/dd").format(today);For more patterns, just read the java.text.SimpleDateFormat API documentation. -
What's wrong with java.util.Date??
Hi all,
I was just practicing a bit of java.util ,when i was compiling my code-
import java.util.Date;
import java.text.SimpleDateFormat;
class DateStamp{
public static void Main(String args[]){
doDate1;
String D;
int D1,D2,D3;
Date dt=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("dd-mm-yyyy");
/*When using method .setDate(x) ,is x an integer or String?can x=2/5/2002 or 2-5-2002?*/
public void doDate1{
dt.setDay(12);
dt.setMonth(12);
dt.setYear(102);
D=dt.getTime();
D.parseInt(D1);D=""
D=sdf.getTime();
D.parseInt(D2);
int D3=D2-D1;
int D3=D3/86400000;/*How do you convert milisec-to-days?*/
D=D3.toString().
System.out.println(D+"days have elapsed since then");
the compiler said this-
File Compiled...
--------------------------- Javac Output ---------------------------
DateStamp.java:7: Invalid expression statement.doDate1;^DateStamp.java:14: Instance variables can't be void: doDate1public void doDate1; ^2 errors
this problem is persistant, and i'm a java newbie ,Does anyone know what's wrong here?
Thanks!
Regards,
aesh83How do you get System date onto a Date variable?Calendar.getInstance().getTime() returns a java.util.Date for the current time. You can also use System.currentTimeMillis() and turn it into a Date.
Will date.after(Date when) method work when Date
variables are in milisecs?Date.after(Date when) compares two date objects. As the JavaDoc says "Returns:
true if and only if the instant represented by this Date object is strictly later than the instant represented by when" To me that says that milliseconds are taken into account, I.E. comparing dates actually compares the date plus the time portion.
>
What methods-
*Convert a date(dd/mm/yy) to milisec?If you look in the javaDoc you'll see "long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object." Calendar also has the getTimeInMillis() method.
*Convert a milisec value to a date(dd/mm/yy)?Calendar.setTimeInMillis(long);
I'm have this little problem.
When using GregorianCalander-
*need to initialize?
*need set today's date?Calendar.getInstance() will return an appropriate Calendar object for the current locale initialized to the current date/time.
*how do you check if a date exceeds 3 weeks?I'm not sure what you mean. There are a couple of roll(...) methods that will allow you to add a unit of time to a date. I.E. you could add three weeks to a date.
To ignore the time portion of a date just set the time to "00:00"
Col -
Convert java.util.Timestamp to a formatted java.util.date
Hi,
I am trying to convert a java.util.TimeStamp date from the DB to a formatted date object. So, how can I convert this TimeStamp into an hourly or daily format that will return me a java.util.Date object? I was trying to convert the TimeStamp using SimpleDateFormat and then parse out to a Date object, but this isn't working. This is what I need
TimeStamp converted to an "Hourly" date object --> 12:00pm
TimeStamp converted to a "Monthly" date object --> MayHi,
I am trying to convert a java.util.TimeStamp date
from the DB to a formatted date object. I don't know what a "formatted date object" is. Do you mean a String?
So, how can
I convert this TimeStamp into an hourly or daily
format that will return me a java.util.Date object?I don't know what you mean when you say "...int an hourly or daily format that will return me a java.util.Date object". A format is a String, are you wanting to parse that into a java.util.Date object?
I was trying to convert the TimeStamp using
SimpleDateFormat and then parse out to a Date
object, but this isn't working. This is what I
need
TimeStamp converted to an "Hourly" date object -->
12:00pmThat's a String then?
A java.sql.Timestamp extends java.util.Date. So if you've a Timestamp, then you can use it as you would a java.util.Date. If you want a String, then as you say use SimpleDateFormat with the appropriate format string.
Good Luck
Lee -
Summary:
JDK 1.7.0_09 and wsimport and xjc that comes with it.
Global JAXB binding to map xs:date to java.util.Date
I have the following external bindings file:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
elementFormDefault="qualified" attributeFormDefault="unqualified"
jaxb:extensionBindingPrefixes="xjc" jaxb:version="2.1">
<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings>
<xjc:serializable />
<jaxb:javaType name="java.util.Date" xmlType="xs:date" parseMethod="au.com.xxx.jaxb.DateAdapter.parseDate" printMethod="au.com.xxx.jaxb.DateAdapter.printDate" />
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>
</xs:schema>The au.com.xxx.jaxb.DateAdapter code is as follows:
package au.com.xxx.jaxb;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.bind.DatatypeConverter;
public class DateAdapter {
public static Date parseDate(String s) {
return DatatypeConverter.parseDate(s).getTime();
public static String printDate(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
return DatatypeConverter.printDate(cal);
}When I run the following wsimport from the command line, I get:
salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
$ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
parsing WSDL...
Generating code...
Compiling code...
C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:13: error: package au.com.xxx.jaxb does not exist
return (au.com.xxx.jaxb.DateAdapter.parseDate(value));
^
C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:17: error: package au.com.xxx.jaxb does not exist
return (au.com.xxx.jaxb.DateAdapter.printDate(value));
^
2 errors
compilation failed, errors should have been reportedWhich means that wsimport or xjc needs to know the classpath to find au.com.xxx.jaxb.DateAdapter.
But how do I pass the classpath from wsimport to the JAXB compiler ?
There is the -B option in wsimport, but I could not get it to work.
If I read it correctly, I should be able to pass the -classpath option to the JAXB compiler from wsimport via -B.
I tried:
salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
$ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -B"-classpath WebContent/WEB-INF/classes" -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
no such JAXB option: -classpath WebContent/WEB-INF/classes
Usage: wsimport [options] <WSDL_URI>
where [options] include:
-b <path> specify jaxws/jaxb binding files or additional schemas
(Each <path> must have its own -b)
-B<jaxbOption> Pass this option to JAXB schema compiler
-catalog <file> specify catalog file to resolve external entity references
supports TR9401, XCatalog, and OASIS XML Catalog format.
-d <directory> specify where to place generated output files
<...snipped...>... where WebContent/WEB-INF/classes is the classpath where au.com.xxx.jaxb.DateAdapter.class could be found. Obviously it did not like it.
Also, why is wsimport generate org.w3._2001.xmlschema.Adapter1.java ? All it is doing is wrapping up the exact same call that I have specified in my DateAdapter. How can I tell wsimport or xjc to NOT create that extra Adapter1.java and simply directly use my DateAdapter ??create additional column of type LONG to represent date.
dateFormat is of type java.util.Date:
long newLongDate = dateFormat.getTime();
select object(b) from MyEntity b where b.MYLONGDATE > ?1 and b.MYLOGDATE <= ?2 -
Exception in thread "main" java.util.NoSuchElementException
Hello there,
I need to store resultset values in arrays.
Following is my code:
(Note : The function uses the jdbc connection with mysql that is return from other function.)
public static void getResultSetInArray(Connection con) throws Exception
Map list = new HashMap();
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("show columns from launchcomm.events");
while(rs.next())
list.put(rs.getString("Field"),rs.getString("Type"));
rs.close();
con.close();
System.out.println("List = " + list + "\n");
Iterator iter = null;
iter = list.keySet().iterator();
System.out.println("iter = " + iter);
String field;
String type;
int i=1;
System.out.println("list size = " + list.size());
while(iter.hasNext() != false)
System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
System.out.println("iter.next() = " + iter.next());
field = (String)iter.next();
type = (String)list.get(iter.next());
Following is my output with error:
List = {folder_name=varchar(50), is_repeat=tinyint(1), footer=text, thankyou_email=text, box_header_bg_color=varchar(25), organization_id=int(11), attendee_delete_right=tinyint(1), show_ticket_remaining=tinyint(1), order_confirmation_email=text, save_for_later=tinyint(1), start_register=tinyint(4), id=int(11), logo=varchar(100), publish=tinyint(1), end_unregister=datetime, owner_id=int(11), confirmation_email=text, audience_id=int(11), event_color_code=varchar(30), showcalendar=tinyint(1), registration_enddate=datetime, directory_name=varchar(20), eventstatus_id=int(11), contact_id=int(11), password_protect=tinyint(1), include_header=tinyint(1), thankyou_page=text, header=text, is_hotel_capacity=tinyint(1), want_close=tinyint(1), travel_housing_request=tinyint(1), box_header_text_color=varchar(25), default_location_id=int(11), end_reg_modification=datetime, user_id=int(11), passkey_eventcode=varchar(255), page_size=int(11), passkey_password=varchar(255), event_capacity=int(11), box_text_color=varchar(25), updated_on=datetime, link_color=varchar(25), ends_on=datetime, hotel_capacity=int(11), template_id=int(11), allow_overlap_session=tinyint(1), starts_on=datetime, reg_another_button=varchar(50), passkey_partnerid=int(11), personalized_url=tinyint(1), hide_start_date=tinyint(1), hide_end_date=tinyint(1), include_footer=tinyint(1), text_color=varchar(25), allow_another_registrant=tinyint(1), passkey_eventid=int(11), resize=tinyint(1), default_closetemplate=tinyint(1), dateformat=text, personalize_agenda=tinyint(1), cssfile_id=int(11), passkey_information=tinyint(1), confirmation_page=text, activate_waitlist=tinyint(1), box_border_color=varchar(25), google_analytics_code=text, show_iframe_design=tinyint(1), confirmation_mail_format=tinyint(1), url=varchar(100), bg_color=varchar(25), package_id=int(11), name=varchar(200), password=varchar(50), capacity=int(11), modify_registration=tinyint(1), is_event_capacity=tinyint(1), include_css=tinyint(1), passkey_username=varchar(255), created_on=datetime, promote_url=varchar(100), page_views=int(11), box_bg_color=varchar(25), title_text_color=varchar(25), registration_open_text=text, require_login=tinyint(1), closetemplate_description=text, registration_startdate=datetime, domain=varchar(200), timezone_id=varchar(100), description=text, tag=varchar(255), allow_unregister=tinyint(1), order_confirmation_page=text, css=text, showmap=tinyint(1)}
iter = java.util.HashMap$KeyIterator@18a47e0
list size = 95
iter.hasNext() = true......1
iter.next() = folder_name
iter.hasNext() = true......2
iter.next() = footer
iter.hasNext() = true......3
iter.next() = box_header_bg_color
iter.hasNext() = true......4
iter.next() = attendee_delete_right
iter.hasNext() = true......5
iter.next() = order_confirmation_email
iter.hasNext() = true......6
iter.next() = start_register
iter.hasNext() = true......7
iter.next() = logo
iter.hasNext() = true......8
iter.next() = end_unregister
iter.hasNext() = true......9
iter.next() = confirmation_email
iter.hasNext() = true......10
iter.next() = event_color_code
iter.hasNext() = true......11
iter.next() = registration_enddate
iter.hasNext() = true......12
iter.next() = eventstatus_id
iter.hasNext() = true......13
iter.next() = password_protect
iter.hasNext() = true......14
iter.next() = thankyou_page
iter.hasNext() = true......15
iter.next() = is_hotel_capacity
iter.hasNext() = true......16
iter.next() = travel_housing_request
iter.hasNext() = true......17
iter.next() = default_location_id
iter.hasNext() = true......18
iter.next() = user_id
iter.hasNext() = true......19
iter.next() = page_size
iter.hasNext() = true......20
iter.next() = event_capacity
iter.hasNext() = true......21
iter.next() = updated_on
iter.hasNext() = true......22
iter.next() = ends_on
iter.hasNext() = true......23
iter.next() = template_id
iter.hasNext() = true......24
iter.next() = starts_on
iter.hasNext() = true......25
iter.next() = passkey_partnerid
iter.hasNext() = true......26
iter.next() = hide_start_date
iter.hasNext() = true......27
iter.next() = include_footer
iter.hasNext() = true......28
iter.next() = allow_another_registrant
iter.hasNext() = true......29
iter.next() = resize
iter.hasNext() = true......30
iter.next() = dateformat
iter.hasNext() = true......31
iter.next() = cssfile_id
iter.hasNext() = true......32
iter.next() = confirmation_page
iter.hasNext() = true......33
iter.next() = box_border_color
iter.hasNext() = true......34
iter.next() = show_iframe_design
iter.hasNext() = true......35
iter.next() = url
iter.hasNext() = true......36
iter.next() = package_id
iter.hasNext() = true......37
iter.next() = password
iter.hasNext() = true......38
iter.next() = modify_registration
iter.hasNext() = true......39
iter.next() = include_css
iter.hasNext() = true......40
iter.next() = created_on
iter.hasNext() = true......41
iter.next() = page_views
iter.hasNext() = true......42
iter.next() = title_text_color
iter.hasNext() = true......43
iter.next() = require_login
iter.hasNext() = true......44
iter.next() = registration_startdate
iter.hasNext() = true......45
iter.next() = timezone_id
iter.hasNext() = true......46
iter.next() = tag
iter.hasNext() = true......47
iter.next() = order_confirmation_page
iter.hasNext() = true......48
iter.next() = showmap
Exception in thread "main" java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:844)
at java.util.HashMap$KeyIterator.next(HashMap.java:877)
at GetDataTypeFromDB.getResultSetInArray(GetDataTypeFromDB.java:57)
at GetDataTypeFromDB.main(GetDataTypeFromDB.java:16)
I am unable to fine the reason for the exception.
Please help me to solve my problem.
Regards,
Thevoice
Edited by: TheVoice on May 14, 2008 12:01 AMTheVoice wrote:
while(iter.hasNext() != false)
System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
System.out.println("iter.next() = " + iter.next());
field = (String)iter.next();
type = (String)list.get(iter.next());
}Your major problem is that iter.next() advances one place every time you call it, so in every iteration of that loop, you advance three steps. The first step is guaranteed to be okay, because you checked it with iter.hasNext(), but the other two are not. In addition, you are in effect "skipping" the printing of two out of every three items.
To print out every item, you probably want to do something like this (call it only one and store it in a variable):
while(iter.hasNext())
String field = (String)iter.next();
System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
System.out.println("iter.next() = " + field);
String type = (String)list.get(field);
}For additional clarity, I would recommend using Generics, Map.entrySet(), and the for-each loop:
public static void getResultSetInArray(Connection con) throws Exception
Map<String,String> list = new HashMap<String,String>();
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("show columns from launchcomm.events");
while(rs.next())
list.put(rs.getString("Field"),rs.getString("Type"));
rs.close();
con.close();
for (Map.Entry<String,String> e : list.entrySet())
String field = e.getKey();
String type = e.getValue();
// do stuff with them
}Edited by: spoon_ on May 14, 2008 7:34 PM
Maybe you are looking for
-
How to avoid focus issue while navigating via Browser Back button
Hi I'm facing some problem in setting focus on Buttons. Please refer application: http://apex.oracle.com/pls/otn/f?p=47869:2 login credentials: Workspace: vsanthanam user: vijay pswd: apex_demo In this application, i have 2 pages. Page#2 has Submit b
-
What is this file and why can't I do anything with it?
I found this file in All my Files today and it's bugging me a bit. It seems to be a Pixelmator file with the same creation date as the file before with, giving me the impression they're linked somehow. The mystery file, however, doesn't have a locati
-
How to add body text to smartform email?
Hi, In release 620, how can you add text to the mail message that is generated from e-mailing a smartform. I need to add a small message to the body of the message in addition to the attachment. i.e. Please find attached your invoice. [attachement.p
-
CN41 report with out values for project dates
Hi Experts The following field values are captured in Table PROJ. a. Finish Date PROJ-PLSEZ b. Forecast Start PROJ-SPROG c. Forecast Finish PROJ-EPROG But the report CN41/CN41N does not show values for these fields. Can anybody give clue to get this
-
I can't open FF and get message: Error: a is undefined
FF won't open, even if in safe mode. Under FF, I get an error box with the message "Error: a is undefined" the error info is "Source File: http://www.google.com/extern_js/f/CgJlbhICdXMrMFo4ACwrMA44ACwrMBc4ACwrMDw4ACwrMFE4ACwrMFk4ACwrMAo4AEBdmgICcHMsK