How to handle different date formats ?

I'm currently writing an application that has to be compatible with different database backends.
But I have some problems with the date/time fields when using Oracle as a db backend:
After searching the forums, I found a solution for my "inserts" problem:
// This is needed because otherwise the db session will be reset with each jdbc call,
// ending the session and nullifying the ALTER SESSION command
con.setAutoCommit( false );
// set the date/time format to what we want it to be
result = stmt.executeQuery("ALTER SESSION SET NLS_DATE_FORMAT = 'dd/mm/yyyy hh24:mi:ss'");
res = stmt.executeUpdate(query);
Where query is something like "INSERT INTO DATE_TEST VALUES ('val1',"val2','val3','25/03/2004 15:59:44');
But when I want to retrieve this data, the timestamp is returned in another format:
result = stmt.executeQuery("SELECT * FROM DATE_TEST");
This gives me "2004-03-25 15:59:44.0" for the timestamp !
when I run exactly the same query in the Oracle SQL*Plus console, I get the correct format:
SQL> SELECT * FROM DATE_TEST;
VAL1 VAL2 VAL3 TIME
val1 val2 val3 25/03/2004 15:59:44
SQL>
I already tried the trick with the NLS_DATE_FORMAT before retrieving the data, but that doesn't seem to do anything.
Any ideas how I can manipulate the format of a DATE field for retrieval ?
Note:
This is what I use:
- Oracle 9i, Release 2 (9.2.0.1.0) for Windows (on windows 2000 Server)
- ojdbc14.jar (Oracle thin jdbc driver)
- j2sdk 1.4.2-04 for my application (currently running on windows server 2003 Enterprise, but is also tested on windows 2000, xp, linux, solaris)

well, in fact I wrote a "dbAdapter" which I use to let my application communicate with a database.
the method I use to retrieve data from the db just reads the resultset row by row, adding each row to a
vector.
each row is represented by a hashtable (colname - colvalue pairs).
Vector result = dbadapter.queryDB("SELECT * FROM DATE_TEST");
the method "query" looks like this:
public Vector queryDB(String query) {
Connection con = null;
ResultSet result = null;
ResultSetMetaData metadata = null;
Vector tableData = new Vector();
Statement stmt = null;
try { // Attempt to load the JDBC driver with newInstance
Class.forName(sDriver).newInstance();
catch (Exception e) { // error
logger.error(logPrefix + "Failed to load current driver.");
if (psStackTrace != null)
e.printStackTrace(psStackTrace);
return tableData;
} // end catch
try {
con = DriverManager.getConnection(sURL, sUsername, sPassword);
// stmt = con.createStatement(); // MySQL
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); // TODO-ORACLE
catch (Exception e) {
logger.error(logPrefix + "problems connecting to " + sURL + ":" + e.getMessage());
if (psStackTrace != null)
e.printStackTrace(psStackTrace);
if (con != null) {
try {
con.close();
catch (Exception e2) {
return tableData;
} // end catch
// execute SQL commands
try {
result = stmt.executeQuery(query);
// first display some metadata
metadata = result.getMetaData();
int numcols = metadata.getColumnCount(); // How many columns?
result.last(); // Move to last row
int numrows = result.getRow();
Hashtable rowData = new Hashtable();
String colValue = "", colName = "";
Object o = null;
for (int a = 0; a < numrows; a++) {
result.absolute(a + 1); // go to row a in resultset
for (byte b = 0; b < numcols; b++) {
o = result.getObject(b + 1);
colName = metadata.getColumnName(b + 1);
if (o == null) {
colValue = "";
else {
colValue = o.toString();
rowData.put(colName, colValue);
tableData.add(rowData.clone());
rowData.clear();
// return result
return tableData;
catch (Exception e) {
logger.error(logPrefix + "problem with SQL sent to " + sURL + ":" + e.getMessage());
logger.debug(logPrefix + "sql: " + query);
if (psStackTrace != null)
e.printStackTrace(psStackTrace);
finally {
try {
stmt.close();
catch (Exception e) {
try {
con.close();
catch (Exception e) {
} // end finally clause
return tableData;
then I display the data using this code (output goes to a logfile):
for (int i = 0; i < result.size(); i++) {
Hashtable tmpResultTable = (Hashtable) result.elementAt(i);
Enumeration enum = tmpResultTable.keys();
while(enum.hasMoreElements()) {
String tmpKey = (String) enum.nextElement();
String tmpValue = (String) tmpResultTable.get(tmpKey);
logger.debug(logPrefix + "\t- " + tmpKey + "=" + tmpValue);
It is correct indeed that I want to keep it as vendor neutral as possible, because other databases will
be added in the (near) future (such as IBM's DB2)
I already thought about formatting it using the SimpleDateFormat class, but then I have to rewrite most
of the code in my dbAdapter, because it doesn't know anything about the field types.
It just launches standard SQL queries and returns the result back to the requesting object

Similar Messages

  • How to extract  different date format in text file

    well, iam new for using regex api(regular expression), In my project i want to extract the different format of date from the text file... date format will be 3rd june 2004, 03-06-2004, june 3rd and so on....
    can any body give me regular expression to extract the date from the text file...
    i will be very grateful..
    kareem

    date format will be 3rd june 2004, 03-06-2004, june 3rd and so on....The only way to do this (without implementing a "mind reader") is to determine in advance all the possible date formats that are possible in your input, and try to interpret each date using each of those formats until one of them passes.
    It's easy enough to handle june 3rd vs 3 june vs 3rd june, but 6/3 vs 3/6, of course, is ambiguous.

  • How to handle Multiple date formats for the same date field in SQL*Loader

    Dear All,
    I got a requirement where I need to get data from a text file and insert the same into oracle table.
    I am using SQL*Loader to populate the data from the text file into my table.
    The file has one field where I am expecting date date data in multiple formats, like dd/mon/yyyy, yyyy/dd/mon, yyyy/mon/dd, ,mm/dd/yyyy, mon/dd/yyyy.
    While using SQL*Loader, I can see Loading is failing for records where we have formats like yyyy/dd/mon, yyyy/mon/dd, mon/dd/yyyy.
    Is there any way in SQL*Loader where we can mention all these date formats so that this date data should go smoothly into the underlying date column in the table.
    Appreciate your response on this.
    Thanks,
    Madhu K.

    The point being made was, are you sure that you can uniquely identify a date format from the value you receieve? Are you sure that the data stored is only of a particular limited set of formats?
    e.g. if you had a value of '07/08/03' how do you know what format that is?
    It could be...
    7th August 2003 (thus assuming it's DD/MM/RR format)
    or
    8th July 2003 (thus assuming it's MM/DD/RR format)
    or
    3rd August 2007 (thus assuming it's RR/MM/DD format)
    or
    8th March 2007 (thus assuming it's RR/DD/MM format)
    or even more obscurely...
    3rd July 2008 (MM/RR/DD)
    or
    7th March 2008 (DD/RR/MM)
    Do you have any information to tell you what formats are valid that would allow you to be specific and know what date format is meant?
    This is a classic example of why dates should be stored on the database using DATE datatype and not VARCHAR2. It can lead to corruption of data, especially if the date can be entered in any format a user wishes.

  • Problem with SQL*Loader and different date formats in the same file

    DB: Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    System: AIX 5.3.0.0
    Hello,
    I'm using SQL*Loader to import semi-colon separated values into a table. The files are delivered to us by a data provider who concatenates data from different sources and this results in us having different date formats within the same file. For example:
    ...;2010-12-31;22/11/1932;...
    I load this data using the following lines in the control file:
    EXECUTIONDATE1     TIMESTAMP     NULLIF EXECUTIONDATE1=BLANKS     "TO_DATE(:EXECUTIONDATE1, 'YYYY-MM-DD')",
    DELDOB          TIMESTAMP     NULLIF DELDOB=BLANKS          "TO_DATE(:DELDOB, 'DD/MM/YYYY')",
    The relevant NLS parameters:
    NLS_LANGUAGE=FRENCH
    NLS_DATE_FORMAT=DD/MM/RR
    NLS_DATE_LANGUAGE=FRENCH
    If I load this file as is the values loaded into the table are 31 dec 2010 and 22 nov *2032*, aven though the years are on 4 digits. If I change the NLS_DATE_FORMAT to DD/MM/YYYY then the second date value will be loaded correctly, but the first value will be loaded as 31 dec *2020* !!
    How can I get both date values to load correctly?
    Thanks!
    Sylvain

    This is very strange, after running a few tests I realized that if the year is 19XX then it will get loaded as 2019, and if it is 20XX then it will be 2020. I'm guessing it may have something to do with certain env variables that aren't set up properly because I'm fairly sure my SQL*Loader control file is correct... I'll run more tests :-(

  • Different Date Formats on CRM and BI Client

    Hi,
    When trying to run the CRM Interactive Report "Accounts with Open Activities", I receive the following error:
    Different date formats on CRM and BI client 01/13/2009 13.01.2009 SC5CLNT200
    Does anybody know how to resolve this error?
    Thanks

    Hi Peter,
    As far as i remember, I had the same issue.
    Once I matched the date format in reporting client using SU01 on default tab with CRM date format, I did't see the error again.
    Did you try restarting the Browser & also relogin GUI.
    Else lets see what else can be done.
    Best Regards
    Shiven

  • How to handle time&date

    can anyone tell me how to handle time&date correctly?using Calendar,GregorianCalendar,TimeZone,Locale
    thank you very much

    This is too large a topic to discuss in depth here. Here is a link to a tutorial on times and dates, and a search link that references many documents on the subject.
    http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html
    http://onesearch.sun.com/search/developers/index.jsp?and=calendar+&nh=100&phr=how+to&qt=&not=&field=&since=&col=javatecharticles&col=javatutorials&col=devall&rf=0&Search.x=20&Search.y=7
    When you have specific questions, just ask.

  • How to change the date format?

    Hi,
    I need to display the data format as(YYYY-MM-DD). But now it displays(2009-1-9)
    Here is my code snippet which i used to display the data format as(2009-1-9)
    *<INPUT TYPE=TEXT NAME="date_submitted" MAXLENGTH=20 SIZE=10 VALUE="" onBlur= "return dateSubmitted()">  (YYYY-MM-DD)*
    *<SCRIPT LANGUAGE="javascript">*
    dateSubmitted()
    *</SCRIPT>*
    function dateSubmitted()
                        if (document.pgUpdate.date_submitted.value == "")
                             date = new Date();     
                             month = date.getMonth() + 1     
                             document.pgUpdate.date_submitted.value =
                                            date.getYear() + "-" + month + "-" + date.getDate();
                        return true;
    Can anybody help me how to change the date format?
    Thanks in advance!

    prit123 wrote:
    use SimpleDateFormat class. The code is :He posted a Javascript related question, not a Java related question.
    Please use forums devoted to Javascript. You're here at a Java/JSP forum.
    There are JS forums at webdeveloper.com and dynamicdrive.com. Good luck.
    String formatPattern = "yyyy-mm-dd";
    SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
    sdf.format(yourdate);yyyy-mm-dd denotes year-minutes-days. Please go read the SimpleDateFormat API as well.

  • In  BDC how you handled header data and item data

    In  BDC how you handled header data and item data

    Raja,
    Can you be more clear ?
    Usually you load the header data one and then loop at the item data and then load the item data.
    This example should help you.
    http://www.sap-img.com/abap/bdc-example-using-table-control-in-bdc.htm
    Regards,
    Ravi
    Note - Please mark all the helpful answers

  • How to define the date format for this date string

    2006-11-13 00:00:00.0
    How to define the date format in control file for sqlldr. "yyyy-mm-dd hh24:mi:ss" or "yyyy-mm-dd hh24:mi:ss.FF1" does not work
    thanks,

    SQL> desc t
    Name                                      Null?    Type
    TS                                                 TIMESTAMP(6)
    SQL> !cat t.ctl
    load data
    into table t
    truncate
    (ts timestamp "YYYY-MM-DD HH24:MI:SS.FF1")
    SQL> !cat t.dat
    2006-11-13 00:00:00.0
    SQL> !sqlldr userid=scott/tiger control=t.ctl data=t.dat log=t.log
    SQL*Loader: Release 10.2.0.3.0 - Production on Fri Sep 7 11:19:28 2007
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Commit point reached - logical record count 1
    SQL> select * from t;
    TS
    13-NOV-06 12.00.00.000000 AMBest regards
    Maxim

  • Different Date Formats in the same "From"

    Hello
    We used different date formats depending on the users language.
    In a report this is simple to implement ... read the date field twice (in different formats dd/mm/yyyy and mm/dd/yyyy) and display only one based on the language.
    I want to be able to do the same in a "form" which updates a date. In this case the about is not allowed.
    Has anyone have solution for this using "APEX" forms or do a need to write a process to achieve this?
    Thanks
    Pete

    Pete,
    You don't specify what version of Application Express you're using, so I'll assume APEX 3.1 or later.
    Are you setting the date format yourself, based upon the user's language?
    1) You could have the application's language derived from Browser, and then APEX would automatically set the NLS_LANGUAGE and NLS_TERRITORY settings accordingly. Then, I would simply use 'DS' as the Application Date Format. For Date Pickers on a form, I would use item type 'Date Picker (use Application Date Format)'.
    2) If you're already determining the date format yourself and you don't want APEX to do it for you, ensure that you are setting this value in an application item (e.g., PETE_DATE_FORMAT). Then, you could still use Application Date Format with a value of &PETE_DATE_FORMAT. (inclusive of the trailing period).
    When you use Application Date Format, the conversion should happen automatically for you so that you don't have to code this yourself on the Form.
    I hope this helps.
    Joel

  • URGENT: XML-SQL: Error parsing different date formats in the same XML file.

    Hi Everyone,
    I have a big problem while using the XML-SQL utility. I have a XML file with different date formats. I get exception like the one below.
    "oracle.xml.sql.OracleXMLSQLException: 'java.text.ParseException: Unparseable date:"
    And the XML file is :
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Info Key="ID">
         <Insert>
              <ID>1</ID>
              <BookingDate>10.12.2001</BookingDate>
              <OpeningTime>19:16</OpeningTime>
         </Insert>
    </Info>
    I have tried using different setDateFormat which is contrary.
    sav.setDateFormat("d.M.y");
    sav.setDateFormat("H:m:s");
    Can someone help me on the same.
    Thanks in advance.
    Subramanian.

    You might have to describe the columns as varchar then modify the table to the right format.

  • How to handle different languages in Illustrator for big clients?

    Hi Guys,
    I need small suggestio for 'How to handle different languages in illustrator for big clients'. For instance; Arabic, this is a language which  needs to be read from right to left instead of left to right. There are  other strange languages as well (Cyrillic, Chinese etc.). It happens  also that when you copy strange languages from a word file it will not  be easy to paste it the correct way in a .ai file. Besides that, it’s  also difficult to do a language check when we are not able to read it!. So,  to make a long story short, I want to figure out how we can deal with multiple language  circles?
    Can you some please give me the solution for this...
    Thanks in advance...
    HARI

    I take it you might come from an arabic background.
    Here is how you can help yourself to some degree.
    Google has a translation feature and service which is at the moment free. It is excellent.
    Secondly if you are working with ME languages you really need the ME version of Illustrator or any other Creative Suites Application in order for it to work properly.
    It, is also best to enable the language and the input for that language for your system on the Mac it is easy you go to the Language and text feature in theSystem Preferences, once enabled you can select the fro the menu bar under the American flag if you are in the US. Thst will appear once you have more than one language selected.
    You select the language input you need and then a font for that language then paste and edit.
    You need fonts on your computer that are of those languages as well.
    How to manage this as a work flow well that is something you will have to work on yourself or hire a consultant who specializes in this area.
    We had a few visit here when they have come across a snafu. So they exists.

  • How to change the date format in xml form?

    hi,
    How to change the date format in xml form?
    For example:  11/20/2008 3:00:03 PM    ->   11-20 03:00
    Any opinions greatly appreciated!
    Thanks.
    Edited by: ke wenxing on Dec 2, 2008 8:33 AM

    You could go to System - User Profile - Own Data would take you to the "maintain user profile screen"
    Click the defaults button and change the date format.This changes date format for all the dates in your login.

  • How to change the date format  YYYYMMDD to MM/DD/YYYY

    Hi ,
    How to change the date format  YYYYMMDD to MM/DD/YYYY .
    Ex :  20071008  to 10/08/2007
    Is there any function module for this ??
    Regards
    Rahul

    Hi Sharma,
    check the code:
    SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-031.
    PARAMETERS: date1 RADIOBUTTON GROUP rad1 DEFAULT 'X', "SAP date format YYYYDDMM
    date2 RADIOBUTTON GROUP rad1, "Date format like aprial31, 2006
    date3 RADIOBUTTON GROUP rad1, "Date format like 31 apr,2006
    date4 RADIOBUTTON GROUP rad1, "Date format like DD/MM/YYYY
    date5 RADIOBUTTON GROUP rad1. "Date format like DD.MM.YYYY
    SELECTION-SCREEN END OF BLOCK b2
    FORM getmonth .
    SELECT mnr
    ktx
    ltx
    INTO TABLE T_month
    FROM t247
    WHERE spras = 'EN'.
    IF sy-subrc NE '0'.
    MESSAGE I "Message - Not able to get month values from the table T247
    ENDIF.
    ENDFORM.
    DATA : temp_date(16) TYPE c,
    temp1_date(60) TYPE c,
    year(4) TYPE c,
    daymonth(11) TYPE c,
    daymonth1(11) TYPE c,
    month(9) TYPE c,
    day(2) TYPE c,
    mon LIKE t247-ktx,
    len TYPE i .
    MOVE date TO temp1_date .
    CONDENSE temp1_date NO-GAPS.
    MOVE temp1_date TO temp_date .
    IF date2 EQ 'X'. "The date format is like Aprial 31, 2007
    CONDENSE temp_date NO-GAPS.
    SPLIT date AT ',' INTO daymonth year.
    IF STRLEN( year ) NE '4'.
    error = 'X'.
    WRITE : 'Invalid date format.'.
    ELSE.
    daymonth1 = daymonth.
    CONDENSE daymonth1 NO-GAPS.
    _len = STRLEN( _daymonth1 ).
    l_len = 13 - len.
    SHIFT daymonth1 RIGHT BY len PLACES.
    CONDENSE daymonth1 NO-GAPS.
    month = daymonth1.
    CONDENSE month NO-GAPS.
    SORT t_month BY monthltx.
    READ TABLE t_month WITH KEY monthltx = month.
    IF sy-subrc <> 0.
    error = 'X'.
    WRITE : 'Invalid date format.' .
    ELSE.
    len = STRLEN( month ).
    CONDENSE daymonth NO-GAPS.
    SHIFT daymonth LEFT BY len PLACES.
    day = daymonth.
    CONDENSE day NO-GAPS.
    CONCATENATE year t_month-monthnumber day INTO o_date.
    ENDIF.
    ENDIF.
    ELSEIF p_date3 EQ 'X'. "The date format is like 31 apr, 2007
    CONDENSE temp_date NO-GAPS.
    SPLIT i_date AT ',' INTO daymonth year.
    IF STRLEN( year ) NE '4'.
    error = 'X'.
    WRITE : 'Invalid date format.'.
    ELSE.
    daymonth1 = daymonth.
    CONDENSE daymonth1 NO-GAPS.
    SHIFT daymonth1 LEFT BY 2 PLACES.
    CONDENSE daymonth1 NO-GAPS.
    month = daymonth1.
    CONDENSE month NO-GAPS.
    TRANSLATE month TO UPPER CASE.
    SORT t_month BY monthstx.
    MOVE month to mon.
    READ TABLE t_month WITH KEY monthstx = mon.
    IF sy-subrc <> 0.
    error = 'X'.
    WRITE : 'Invalid date format.' .
    ELSE.
    CONDENSE daymonth NO-GAPS.
    day = daymonth+0(2).
    CONDENSE day NO-GAPS.
    CONCATENATE year t_month-monthnumber day INTO o_date.
    ENDIF.
    ENDIF.
    ELSEIF p_date4 EQ 'X' OR p_date5 EQ 'X'. "Date format is like DD.MM.YYYY or DD/MM/YYYY
    CONDENSE temp_date NO-GAPS.
    IF STRLEN( temp_date ) EQ 10.
    o_date0(4) = temp_date6(4).
    o_date4(2) = temp_date3(2).
    o_date6(2) = temp_date0(2).
    ELSE.
    error = 'X'.
    WRITE : 'Invalid date format.' .
    ENDIF.
    ENDIF.
    IF STRLEN( o_date ) NE '8'.
    error = 'X'.
    WRITE : 'Invalid date format.'.
    ENDIf.
    ENDFORM. " f0100_conv_date
    Reward if helpful.
    Regards,
    Harini.S

  • How to handle different Unit of measures in ALV reports? Quantity/Price

    Anyone knows how to handle different unit of measures for quantity or price in hierarchy ALV reports?

    hi,
    use the below fields:
    Link to measurement unit
    •qfieldname (measurement unit field name)
    only relevant for quantity columns with unit link.
    Name of the internal output table field containing the measurement unit associated with the quantity field FIELDCAT-FIELDNAME.
    The field in FIELDCAT-QFIELDNAME must have its own field catalog entry.
    •qtabname (internal measurement unit field output table)
    value set: SPACE, output table field name
    Name of the internal output table containing the FIELDCAT-QFIELDNAME field.
    regards,
    madhumitha

Maybe you are looking for

  • Error deploying PAR file from Developer Studio (NW04)

    Hello, i've got a problem while trying to deploy a PAR file from NW Developer Studio. The PAR Export function says "Unable to connect to the Portal", the portal itself gives the following response: "ERROR: Upload failed - exception caught: com.sappor

  • Erasing hard drive problems on macbook pro

    My brand new macbook pro was working very slowly for about a day and then just froze so I restarted it. But then when it was trying to turn on it was just a gray screen with a file and a question mark on it, which I read means it can't find the hard

  • Message Archiving for the Adapter Engine

    Hi, we have configured archiving for Integration Engine (SXMB_MONI) messages on the Production XI System. is it necessary to configure Message Archiving for the Adapter Engine also ? in which scenarios archived adapter messages are useful ? are there

  • Wireless mouse

    My might mouse scroll ball has stopped functioning -- will not scroll down. I have tried cleaning it, etc.. it work when upside down and I'm rolling it on paper to clean. Is there a better mouse that is compatible with the iMAC?

  • Using Windows Media Player, but my phone automatic...

    Sorry the description is so confusing. I have used Windows Media player successfully several times to transfer music to my Nokia 7510. However, now whenever I plug into my computer, rather than allowing me to choose from 3 options, one of which is "P