Search Results

Search found 135 results on 6 pages for 'simpledateformat'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Convert date time value to expected with SimpleDateFormat

    - by Khoi Nguyen
    I have an issue with converting a date time value to expected one with SimpleDateFormat (java), my expected format is MM/yyyy, and I want to convert 2 values to only 1 format MM-yyyy for example 05-2012 yyyy-MM for example 2012-05 ouput is 05/2012. I implemented something look like following String expiry = "2012-01"; try { result = convertDateFormat(expiry, "MM-yyyy", expectedFormat); } catch (ParseException e) { try { result = convertDateFormat(expiry, "yyyy-MM", expectedFormat); } catch (ParseException e1) { e1.printStackTrace(); } e.printStackTrace(); } private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException { SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern); Date d = normalFormat.parse(date); SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern); return cardFormat.format(d); } Now, the return value is 6808, I don't know why. Kindly anyone help me on this case.

    Read the article

  • How to insert sepcial characters in SimpleDateFormat?

    - by sword101
    hey guys i want to insert the word 'at' in the SimpleDateFormat so the date would be something like: Wed, 26 May 2010 at 11:17am i could able to make it without the at like: Wed, 26 May 2010 11:17am using SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy hh:mma"); so any ideas how to insert the word at to make it in the desired format?

    Read the article

  • Parsing custom time format with SimpleDateFormat

    - by ggrigery
    I'm having trouble parsing a date format that I'm getting back from an API and that I have never seen (I believe is a custom format). An example of a date: /Date(1353447000000+0000)/ When I first encountered this format it didn't take me long to see that it was the time in milliseconds with a time zone offset. I'm having trouble extracting this date using SimpleDateFormat though. Here was my first attempt: String weirdDate = "/Date(1353447000000+0000)/"; SimpleDateFormat sdf = new SimpleDateFormat("'/Date('SSSSSSSSSSSSSZ')/'"); Date d1 = sdf.parse(weirdDate); System.out.println(d1.toString()); System.out.println(d1.getTime()); System.out.println(); Date d2 = new Date(Long.parseLong("1353447000000")); System.out.println(d2.toString()); System.out.println(d2.getTime()); And output: Tue Jan 06 22:51:41 EST 1970 532301760 Tue Nov 20 16:30:00 EST 2012 1353447000000 The date (and number of milliseconds parsed) is not even close and I haven't been able to figure out why. After some troubleshooting, I discovered that the way I'm trying to use SDF is clearly flawed. Example: String weirdDate = "1353447000000"; SimpleDateFormat sdf = new SimpleDateFormat("S"); Date d1 = sdf.parse(weirdDate); System.out.println(d1.toString()); System.out.println(d1.getTime()); And output: Wed Jan 07 03:51:41 EST 1970 550301760 I can't say I've ever tried to use SDF in this way to just parse a time in milliseconds because I would normally use Long.parseLong() and just pass it straight into new Date(long) (and in fact the solution I have in place right now is just a regular expression and parsing a long). I'm looking for a cleaner solution that I can easily extract this time in milliseconds with the timezone and quickly parse out into a date without the messy manual handling. Anyone have any ideas or that can spot the errors in my logic above? Help is much appreciated.

    Read the article

  • Java: Extend SimpleDateFormat with new pattern letters

    - by Adam Matan
    Java's SimpleDateFormat is used to format a Date object to a string. The formatter supports various pattern letters, which denote textual representation of a Date field. For example, yy is two-letter year, yyyy is four-letter year, and E is day of week. For example, A SimpleDateFormat initialized with yyyy.MM.dd G 'at' HH:mm:ss z will format a date to something like 2001.07.04 AD at 12:08:56 PDT. I would like to add some pattern letters to SimpleDateFormat. For example, want C to denote Hebrew weekday (??? ?????, ??? ???, ...). What's the right way to extend SimpleDateFormat with these new pattern letters? The only online example I could find seems somewhat complicated. I can live with formatting only, without parsing.

    Read the article

  • simpledateformat parsing date with 'Z' literal

    - by DanInDC
    I am trying to parse a date that looks like this: 2010-04-05T17:16:00Z This is a valid date per http://www.ietf.org/rfc/rfc3339.txt. The 'Z' literal "imply that UTC is the preferred reference point for the specified time." If I try to parse it using SimpleDateFormat and this pattern: yyyy-MM-dd'T'HH:mm:ss It will be parsed as a Mon Apr 05 17:16:00 EDT 2010 SimpleDateFormat is unable to parse the string with these patterns: yyyy-MM-dd'T'HH:mm:ssz yyyy-MM-dd'T'HH:mm:ssZ I can explicitly set the TimeZone to use on the SimpleDateFormat to get the expected output, but I don't think that should be necessary. Is there something I am missing? Is there an alternative date parser?

    Read the article

  • SimpleDateFormat

    - by manu
    Hi, The following code is giving me the parsed date as "Wed Jan 13 00:00:00 EST 2010" instead of "Wed Jun 13 00:00:00 EST 2010". Any ideas much appreciated. SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss"); String str = "2010-06-13T00:00:00"; Date date = sf.parse(str); System.out.println(" Date " + date.toString());

    Read the article

  • Getting pattern string from java SimpleDateFormat

    - by D Lawson
    I have a SimpleDateFormat object that I retrieve from some internationalization utilities. Parsing dates is all fine and good, but I would like to be able show a formatting hint to my users like "MM/dd/yyyy". Is there a way to get the formatting pattern from a SimpleDateFormat object?

    Read the article

  • Why Java SimpleDateFormat().parse() is printing weird formate?

    - by MAK
    My input is String formated as the following: 3/4/2010 10:40:01 AM 3/4/2010 10:38:31 AM My code is: DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss aa"); try { Date today = dateFormat.parse(time); System.out.println("Date Time : " + today); } catch (ParseException e) { e.printStackTrace(); } the output is: Sun Jan 03 10:38:31 AST 2010 Sun Jan 03 10:40:01 AST 2010 I'm not sure from where the day (Sun) came from? or (AST)? and why the date is wrong? I just wanted to keep the same format of the original String date and make it into a Date object. I'm using Netbeans 6.8 Mac version.

    Read the article

  • Why Java SimpleDateFormat().parse() is giving weird formate?

    - by MAK
    My input is String formated as the following: 3/4/2010 10:40:01 AM 3/4/2010 10:38:31 AM My code is: DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss aa"); try { Date today = dateFormat.parse(time); System.out.println("Date Time : " + today); } catch (ParseException e) { e.printStackTrace(); } the output is: Sun Jan 03 10:38:31 AST 2010 Sun Jan 03 10:40:01 AST 2010 I'm not sure from where the day (Sun) came from? or (AST)? and why the date is wrong? I just wanted to keep the same format of the original String date and make it into a Date object. I'm using Netbeans 6.8 Mac version.

    Read the article

  • Java > SimpleDateFormat > Month + 1 Why ?

    - by Natim
    Hello, I am using SimpleDateFormat to display a Calendar like this : public String getDate() { String DATE_FORMAT = "EEEE, dd/MM/yyyy HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); System.err.println(date.getTime().getMonth()); return sdf.format(date.getTime()); } The shell returns 6 and the display : mardi, 06/07/2010 12:44:52 It can't be possible ? Why ? Thanks

    Read the article

  • SimpleDateFormat give inconsistent results

    - by Julien Gagnet
    I am trying to parse a date and I am getting different results when I run the code locally/BST compare to a server in Paris/CEST. I've reproduced the issue in a the following sample. This is trying to parse the start date for the Australian Grand Prix. TimeZone tz = TimeZone.getTimeZone("AET"); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH mm"); dateFormat.setTimeZone(tz); long time = dateFormat.parse("28/03/2010 17 00").getTime(); System.out.println("Time "+time); It seems like I am setting the timezone correctly on the date format and the current timezone shouldn't be affecting the code. But locally it prints 1269756000000 and in Paris 1269759600000. Any idea?

    Read the article

  • Is this a Java DateFormat bug?

    - by anonymous
    The pattern is "dd-MM-yyyy" I think the string "01-01-2010mwwwwwwwwwwwwwww" does not satisfy the pattern, but the following code shows the contrary. Anyone can explain why? public static void main(String[] args) throws Exception { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date date = df.parse("01-01-2010mwwwwwwwwwwwwwww"); System.out.println(date); } Thanks

    Read the article

  • how to parse a Date string to java.Date

    - by hguser
    Hi: I have a date string and I wang to parse it to normal date use the java Date API,the following is my code: public static void main(String[] args) { String date="2010-10-02T12:23:23Z"; String pattern="yyyy-MM-ddThh:mm:ssZ"; SimpleDateFormat sdf=new SimpleDateFormat(pattern); try { Date d=sdf.parse(date); System.out.println(d.getYear()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } However I got a exception:java.lang.IllegalArgumentException: Illegal pattern character 'T' So I wonder if i have to split the string and parse it manually? BTW, I have tried to add a single quote character on either side of the T: String pattern="yyyy-MM-dd'T'hh:mm:ssZ"; It also does not work.

    Read the article

  • convert String "11-10-10 12:00:00" into Date Object

    - by Mahendra Athneria
    Hi, I want to convert String "11-10-10 12:00:00" into Date object but i am not able to do so. can you please help me out? below is the code snippet. i have the Date obj which has the value = Mon Oct 11 00:00:00 IST 2010 DateFormat newDateFormat = new SimpleDateFormat("dd-MM-yy hh:mm:ss"); String strDate = newDateFormat.format(tempDate); //**i got strDate as strDate is : 11-10-10 12:00:00** DateFormat newDateFormat1 = new SimpleDateFormat("dd-MM-yy hh:mm:ss"); try { tempDate = newDateFormat1.parse(strDate); // **getting tempDate as - Mon Oct 11 00:00:00 IST 2010** } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Can someone help me to solve this issue? Regards, Mahendra Athneria Mumbai, India

    Read the article

  • Why are months off by one with Java SimpleDateFormat ?

    - by Natim
    Hello, I am using SimpleDateFormat to display a Calendar like this : public String getDate() { String DATE_FORMAT = "EEEE, dd/MM/yyyy HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); System.err.println(date.getTime().getMonth()); return sdf.format(date.getTime()); } The shell returns 6 and the display : mardi, 06/07/2010 12:44:52 It can't be possible ? Why ? Thanks

    Read the article

  • Why am I getting a ParseException when using SimpleDateFormat to format a date and then parse it?

    - by Greg
    I have been debugging some existing code for which unit tests are failing on my system, but not on colleagues' systems. The root cause is that SimpleDateFormat is throwing ParseExceptions when parsing dates that should be parseable. I created a unit test that demonstrates the code that is failing on my system: import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import junit.framework.TestCase; public class FormatsTest extends TestCase { public void testParse() throws ParseException { DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z"); formatter.setTimeZone(TimeZone.getDefault()); formatter.setLenient(false); formatter.parse(formatter.format(new Date())); } } This test throws a ParseException on my system, but runs successfully on other systems. java.text.ParseException: Unparseable date: "20100603100243.118 -0600" at java.text.DateFormat.parse(DateFormat.java:352) at FormatsTest.testParse(FormatsTest.java:16) I have found that I can setLenient(true) and the test will succeed. The setLenient(false) is what is used in the production code that this test mimics, so I don't want to change it.

    Read the article

  • How to calculate the time difference between two time fields , with respect to the date changes

    - by Tiru
    I want to calculate the time difference.I have three EditTexts , I want to input the times in the first two edittexts in HH:MM format. And then calculate the time difference and the result will show on third edittext field in same format. If the date changes, the time difference will calculate according that, i.e If first time = 23:00 and second time = 01:00 then, the time difference = 02:00 hours public class TimeCalculate extends Activity { private String mBlock; private String mBlockoff; private String mBlockon ; // String mHours, mMinutes; Date date1, date2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); EditText blockoff = (EditText) findViewById(R.id.blockoff); mBlockoff = blockoff.getText().toString(); EditText blockon = (EditText) findViewById(R.id.blockon); mBlockon = blockon.getText().toString(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm"); try { date1 = simpleDateFormat.parse(mBlockoff); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { date2 = simpleDateFormat.parse(mBlockon); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } mBlock = getDifference(date1, date2); EditText block = (EditText) findViewById(R.id.block); block.setText(mBlock.toString()); } public static String getDifference(Date startTime, Date endTime) { if (startTime == null) return "corrupted"; Calendar startDateTime = Calendar.getInstance(); startDateTime.setTime(startTime); Calendar endDateTime = Calendar.getInstance(); endDateTime.setTime(endTime); long milliseconds1 = startDateTime.getTimeInMillis(); long milliseconds2 = endDateTime.getTimeInMillis(); long diff = milliseconds2 - milliseconds1; /*int hours = (int)diff / (60 * 60 * 1000); int minutes = (int) (diff / (60 * 1000)); minutes = minutes - 60 * hours; long seconds = diff / (1000); */ //timeDiff = DateUtils.formatElapsedTime(seconds); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM"); Date date = new Date(diff); return simpleDateFormat.format(date); } } I executed this code ,but gives error as Source not found.I think error at getDifference method.Please give any other logic

    Read the article

  • Openx api Advertiser statistics call [migrated]

    - by Sameer
    I am trying to write a jsp application which will establish the xmlrpc connection with openxapi and return the values. I am using openxapi v1 Here I get the dates through a datepicker and then convert to date format: `String dateStr = request.getParameter("datum1"); SimpleDateFormat formater = new SimpleDateFormat("dd-MM-yyyy"); Date result1 = formater.parse(dateStr); String dateStr2 = request.getParameter("datum2"); SimpleDateFormat formater2 = new SimpleDateFormat("dd-MM-yyyy"); Date result2 = formater2.parse(dateStr2);` Then I call the service provided by openxapi (Advertiser Daily Statistics) (sessionID, advertiserID, from date, to date) Object[] objects1=(Object[])client.execute("advertiserDailyStatistics", new Object[]{sessionId,3,result1,result2});

    Read the article

  • Simple Android Binary Text Clock

    - by Hristo
    Hello, I want to create a simple android binary clock but my application crashes. I use 6 textview fields: 3 for the decimal and 3 for the binary representation of the current time (HH:mm:ss). Here's the code: import java.text.SimpleDateFormat; import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Binary extends Activity implements Runnable { Thread runner; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (runner == null) { //start the song runner = new Thread(this); runner.start(); } } @Override public void run() { TextView hours_dec = (TextView) findViewById(R.id.hours_dec); TextView mins_dec = (TextView) findViewById(R.id.mins_dec); TextView secs_dec = (TextView) findViewById(R.id.secs_dec); TextView hours_bin = (TextView) findViewById(R.id.hours_bin); TextView mins_bin = (TextView) findViewById(R.id.mins_bin); TextView secs_bin = (TextView) findViewById(R.id.secs_bin); SimpleDateFormat hours_sdf = new SimpleDateFormat("HH"); SimpleDateFormat mins_sdf = new SimpleDateFormat("mm"); SimpleDateFormat secs_sdf = new SimpleDateFormat("ss"); Calendar cal = Calendar.getInstance(); while (runner != null) { WaitAMoment(); cal.getTime(); hours_dec.setText(hours_sdf.format(cal.getTime())); mins_dec.setText(mins_sdf.format(cal.getTime())); secs_dec.setText(secs_sdf.format(cal.getTime())); hours_bin.setText(String.valueOf(Integer.toBinaryString(Integer.parseInt((String) hours_dec.getText())))); mins_bin.setText(String.valueOf(Integer.toBinaryString(Integer.parseInt((String) mins_dec.getText())))); secs_bin.setText(String.valueOf(Integer.toBinaryString(Integer.parseInt((String) secs_dec.getText())))); } } protected void WaitAMoment() { try { Thread.sleep(100); } catch (InterruptedException e) { }; } }`

    Read the article

  • Dynamically Changing the Display Names of Menus and Popups

    - by Geertjan
    Very interesting thing and handy to know when needed is the fact that "menuText" and "popupText" (from org.openide.awt.ActionRegistration) can be changed dynamically, via "putValue" as shown below for "popupText". The Action class, in this case, needs to be eager, hence you won't receive the object of interest via the constructor, but you can easily use the global Lookup for that purpose instead, as also shown below. import java.awt.event.ActionEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.AbstractAction; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectInformation; import org.netbeans.api.project.ProjectUtils; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.Utilities; @ActionID( category = "Project", id = "org.ptt.DemoProjectAction") @ActionRegistration( lazy = false, displayName = "NOT-USED") @ActionReference(path = "Projects/Actions", position = 0) public final class DemoProjectAction extends AbstractAction{ private final ProjectInformation context; public DemoProjectAction() { putValue("popupText", "Select Me To See Current Time!"); context = ProjectUtils.getInformation( Utilities.actionsGlobalContext().lookup(Project.class)); } @Override public void actionPerformed(ActionEvent e) { refresh(); } protected void refresh() { DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); String formatted = formatter.format(System.currentTimeMillis()); putValue("popupText", "Time: " + formatted + " (" + context.getDisplayName() +")"); } } Now, let's do something semi useful and display, in the popup, which is available when you right-click a project, the time since the last change was made anywhere in the project, i.e., we can listen recursively to any changes done within a project and then update the popup with the newly acquired information, dynamically: import java.awt.event.ActionEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.AbstractAction; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.filesystems.FileAttributeEvent; import org.openide.filesystems.FileChangeListener; import org.openide.filesystems.FileEvent; import org.openide.filesystems.FileRenameEvent; import org.openide.util.Utilities; @ActionID( category = "Project", id = "org.ptt.TrackProjectTimerAction") @ActionRegistration( lazy = false, displayName = "NOT-USED") @ActionReference( path = "Projects/Actions", position = 0) public final class TrackProjectTimerAction extends AbstractAction implements FileChangeListener { private final Project context; private Long startTime; private Long changedTime; private DateFormat formatter; public TrackProjectTimerAction() { putValue("popupText", "Enable project time tracker"); this.formatter = new SimpleDateFormat("HH:mm:ss"); context = Utilities.actionsGlobalContext().lookup(Project.class); context.getProjectDirectory().addRecursiveListener(this); } @Override public void actionPerformed(ActionEvent e) { startTimer(); } protected void startTimer() { startTime = System.currentTimeMillis(); String formattedStartTime = formatter.format(startTime); putValue("popupText", "Timer started: " + formattedStartTime + " (" + ProjectUtils.getInformation(context).getDisplayName() + ")"); } @Override public void fileChanged(FileEvent fe) { changedTime = System.currentTimeMillis(); formatter = new SimpleDateFormat("mm:ss"); String formattedLapse = formatter.format(changedTime - startTime); putValue("popupText", "Time since last change: " + formattedLapse + " (" + ProjectUtils.getInformation(context).getDisplayName() + ")"); startTime = changedTime; } @Override public void fileFolderCreated(FileEvent fe) {} @Override public void fileDataCreated(FileEvent fe) {} @Override public void fileDeleted(FileEvent fe) {} @Override public void fileRenamed(FileRenameEvent fre) {} @Override public void fileAttributeChanged(FileAttributeEvent fae) {} }

    Read the article

  • Javascript DateFormat for different timezones

    - by Elie
    I'm a Java developer and I'm used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone. Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); System.out.println(sdf.format(date)); // Prints date in Los Angeles sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago")); System.out.println(sdf.format(date)); // Prints same date in Chicago SimpleDateFormat is a pretty neat solution in Java but unfortunately I can't find any similar alternative in Javascript. I'm extending the Date prototype in Javascript to do exactly the same. I have dates in Unix format but I want to format them in different timezones. Date.prototype.format = function(format, timezone) { // Now what? return formattedDate; } I'm looking for a neat way to do this rather than a hack. Thanks

    Read the article

  • java.sql.SQLException: Operation not allowed after ResultSet closed

    - by javatraniee
    Why am I getting an Resultset already closed error? public class Server implements Runnable { private static int port = 1600, maxConnections = 0; public static Connection connnew = null; public static Connection connnew1 = null; public static Statement stnew, stnew1, stnew2, stnew3, stnew4; public void getConnection() { try { Class.forName("org.gjt.mm.mysql.Driver"); connnew = DriverManager.getConnection("jdbc:mysql://localhost/db_alldata", "root", "flashkit"); connnew1 = DriverManager.getConnection("jdbc:mysql://localhost/db_main", "root", "flashkit"); stnew = connnew.createStatement(); stnew1 = connnew.createStatement(); stnew2 = connnew1.createStatement(); stnew3 = connnew1.createStatement(); stnew4 = connnew1.createStatement(); } catch (Exception e) { System.out.print("Get Connection Exception---" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "----- > " + e); } } public void closeConnection() { try { if (!(connnew.isClosed())) { stnew.close(); stnew1.close(); connnew.close(); } if (!(connnew1.isClosed())) { stnew2.close(); stnew3.close(); stnew4.close(); connnew1.close(); } } catch (Exception e) { System.out.print("Close Connection Closing Exception-----" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "------->" + e); } } Server() { try { } catch (Exception ee) { System.out.print("Server Exceptions in main connection--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "------>" + ee); } } public static void main(String[] args) throws SQLException { int i = 0; Server STUD = new Server(); STUD.getConnection(); try { ServerSocket listener = new ServerSocket(port); Socket server; while ((i++ < maxConnections) || (maxConnections == 0)) { @SuppressWarnings("unused") doComms connection; server = listener.accept(); try { ResultSet checkconnection = stnew4 .executeQuery("select count(*) from t_studentdetails"); if (checkconnection.next()) { // DO NOTHING IF EXCEPTION THEN CLOSE ALL CONNECTIONS AND OPEN NEW // CONNECTIONS } } catch (Exception e) { System.out.print("Db Connection Lost Closing And Re-Opning It--------" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "--------" + e); STUD.closeConnection(); STUD.getConnection(); } doComms conn_c = new doComms(server, stnew, stnew1, stnew2, stnew3); Thread t = new Thread(conn_c); t.start(); } } catch (IOException ioe) { System.out.println("Main IOException on socket listen: " + ioe); } } public void run() { } } class doComms implements Runnable { private Socket server; private String input; static Connection conn = null; static Connection conn1 = null; static Statement st, st1, st2, st3; doComms(Socket server, Statement st, Statement st1, Statement st2, Statement st3) { this.server = server; doComms.st = st; doComms.st1 = st1; doComms.st2 = st2; doComms.st3 = st3; } @SuppressWarnings("deprecation") public void run() { input = ""; // char ch; try { DataInputStream in = new DataInputStream(server.getInputStream()); OutputStreamWriter outgoing = new OutputStreamWriter(server.getOutputStream()); while (!(null == (input = in.readLine()))) { savetodatabase(input, server.getPort(), outgoing); } } catch (IOException ioe) { System.out.println("RUN IOException on socket listen:-------" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "----- " + ioe); ioe.printStackTrace(); } } public void savetodatabase(String line, int port1, OutputStreamWriter outgoing) { try { String Rollno = "-", name = "-", div = "-", storeddate = "-", storedtime = "-", mailfrom = ""; String newline = line; String unitid = "-"; storeddate = new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()); storedtime = new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()); String sql2 = "delete from t_currentport where PortNumber='" + port1 + "''"; st2.executeUpdate(sql2); sql2 = "insert into t_currentport (unitid, portnumber,thedate,thetime) values >('" + unitid + "','" + port1 + "','" + storeddate + "','" + storedtime + "')"; st2.executeUpdate(sql2); String tablename = GetTable(); String sql = "select * from t_studentdetails where Unitid='" + unitid + "'"; ResultSet rst = st2.executeQuery(sql); if (rst.next()) { Rollno = rst.getString("Rollno"); name = rst.getString("name"); div = rst.getString("div"); } String sql1 = "insert into studentInfo StoredDate,StoredTime,Subject,UnitId,Body,Status,Rollno,div,VehId,MailDate,MailTime,MailFrom,MailTo,Header,UnProcessedStamps) values('" + storeddate + "','" + storedtime + "','" + unitid + "','" + unitid + "','" + newline + "','Pending','" + Rollno + "','" + div + "','" + name + "','" + storeddate + "','" + storedtime + "','" + mailfrom + "','" + mailfrom + "','-','-')"; st1.executeUpdate(sql1); } catch (Exception e) { System.out.print("Save to db Connection Exception--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-->" + e); } } }

    Read the article

  • ResultSet Already closed error

    - by javatraniee
    why am i getting an error of resultset already closed error public class Server implements Runnable { private static int port=1600, maxConnections=0; public static Connection connnew=null; public static Connection connnew1=null; public static Statement stnew,stnew1,stnew2,stnew3,stnew4; public void getConnection() { try{ Class.forName("org.gjt.mm.mysql.Driver"); connnew= DriverManager.getConnection("jdbc:mysql://localhost/db_alldata","root","flashkit"); connnew1= DriverManager.getConnection("jdbc:mysql://localhost/db_main","root","flashkit"); stnew=connnew.createStatement(); stnew1=connnew.createStatement(); stnew2=connnew1.createStatement(); stnew3=connnew1.createStatement(); stnew4=connnew1.createStatement(); }catch (Exception e) { System.out.print("Get Connection Exception---"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"----- "+e); } } public void closeConnection() { try{ if(!(connnew.isClosed())) { stnew.close(); stnew1.close(); connnew.close(); } if(!(connnew1.isClosed())) { stnew2.close(); stnew3.close(); stnew4.close(); connnew1.close(); } }catch (Exception e) { System.out.print("Close Connection Closing Exception-----"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-------"+e); } } Server() { try{ }catch(Exception ee) { System.out.print("Server Exceptions in main connection--"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"------"+ee); } } public static void main(String[] args) throws SQLException { int i=0; Server STUD= new Server(); STUD.getConnection(); try { ServerSocket listener = new ServerSocket(port); Socket server; while((i++ < maxConnections) || (maxConnections == 0)) { @SuppressWarnings("unused") doComms connection; server = listener.accept(); try{ ResultSet checkconnection=stnew4.executeQuery("select count(*) from t_studentdetails"); if(checkconnection.next()) { //DO NOTHING IF EXCEPTION THEN CLOSE ALL CONNECTIONS AND OPEN NEW CONNECTIONS } }catch (Exception e) { System.out.print("Db Connection Lost Closing And Re-Opning It--------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"--------"+e); STUD.closeConnection(); STUD.getConnection(); } doComms conn_c= new doComms(server,stnew,stnew1,stnew2,stnew3); Thread t = new Thread(conn_c); t.start(); } }catch (IOException ioe) { System.out.println("Main IOException on socket listen: " + ioe); } } public void run() { } } class doComms implements Runnable { private Socket server; private String input; static Connection conn=null; static Connection conn1=null; static Statement st,st1,st2,st3; doComms(Socket server, Statement st,Statement st1,Statement st2,Statement st3 ) { this.server=server; doComms.st=st; doComms.st1=st1; doComms.st2=st2; doComms.st3=st3; } @SuppressWarnings("deprecation") public void run () { input=""; //char ch; try { DataInputStream in = new DataInputStream (server.getInputStream()); OutputStreamWriter outgoing=new OutputStreamWriter(server.getOutputStream()); while(!(null==(input=in.readLine()))) { savetodatabase(input,server.getPort(),outgoing); } //server.close(); } catch (IOException ioe) { System.out.println("RUN IOException on socket listen:-------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"----- " + ioe); ioe.printStackTrace(); } } public void savetodatabase(String line, int port1, OutputStreamWriter outgoing) { try { String Rollno="-",name="-",div="-",storeddate="-",storedtime="-",mailfrom=""; String newline=line; String unitid="-"; storeddate=new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()); storedtime=new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()); String sql2="delete from t_currentport where PortNumber='"+port1+"''"; st2.executeUpdate(sql2); sql2="insert into t_currentport (unitid, portnumber,thedate,thetime) values ('"+unitid+"','"+port1+"','"+storeddate+"','"+storedtime+"')"; st2.executeUpdate(sql2); String tablename=GetTable(); String sql="select * from t_studentdetails where Unitid='"+unitid+"'"; ResultSet rst=st2.executeQuery(sql); if(rst.next()) { Rollno=rst.getString("Rollno"); name=rst.getString("name"); div=rst.getString("div"); } String sql1="insert into studentInfo StoredDate,StoredTime,Subject,UnitId,Body,Status,Rollno,div,VehId,MailDate,MailTime,MailFrom,MailTo,Header,UnProcessedStamps) values('"+storeddate+"','"+storedtime+"','"+unitid+"','"+unitid+"','"+newline+"','Pending','"+Rollno+"','"+div+"','"+name+"','"+storeddate+"','"+storedtime+"','"+mailfrom+"','"+mailfrom+"','-','-')"; st1.executeUpdate(sql1); }catch(Exception e) { System.out.print("Save to db Connection Exception--"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-->"+e); } } }

    Read the article

  • How can change my code to can user insert numbers of year and days ?

    - by MANAL
    I make code to calculate the date of today and the date for two years ago before the day of today and also calculate day before 5 days. I want user insert the numbers of years and days to make compare between date of today . import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; import java.util.Scanner; public class Calendar1 { private static void doCalendarTime() { System.out.print("*************************************************"); Date now = Calendar.getInstance().getTime(); System.out.print(" \n Calendar.getInstance().getTime() : " + now); System.out.println(); } private static void doSimpleDateFormat() { System.out.print("*************************************************"); System.out.print("\n\nSIMPLE DATE FORMAT\n"); System.out.print("*************************************************"); // Get today's date Calendar now = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.print(" \n It is now : " + formatter.format(now.getTime())); System.out.println(); } private static void doAdd() { System.out.println("ADD / SUBTRACT CALENDAR / DATEs"); System.out.println("================================================================="); // Get today's date Calendar now = Calendar.getInstance(); Calendar working; SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); working = (Calendar) now.clone(); working.add(Calendar.DAY_OF_YEAR, - (365 * 2)); System.out.println (" Two years ago it was: " + formatter.format(working.getTime())); working = (Calendar) now.clone(); working.add(Calendar.DAY_OF_YEAR, + 5); System.out.println(" In five days it will be: " + formatter.format(working.getTime())); System.out.println(); } public static void main(String[] args) { System.out.println(); doCalendarTime(); doSimpleDateFormat(); doAdd(); } } help me .

    Read the article

1 2 3 4 5 6  | Next Page >