different date format in java after fetching from oracle - java

In my db max date is as : 27-FEB-12
when i am fetching data by java from db that is:
select to_char(max(CREATE_DT),'dd-mm-yyyy') from PROFILE_DETAILS;
gives me 2012-02-27 00:00:00.0
How can i convert it to: 27-FEB-12( i am trying to use indian date format)
Any idea please

I don't know why you need to_char function in your query. If you are fetching data by jdbc, oracle could give you Date object. It is in your case much easier to convert into different format (String) in future.
anyway based on your current requirement, with to_char, you get a String 2012-02-27 00:00:00.0. now you want to get another string 27-FEB-12. you could do something like below(exception handling was omitted):
final String s = "2012-02-27 00:00:00.0";
String newDateString = new SimpleDateFormat("dd-MMM-yy").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(s));
this will give you 27-Feb-12

String strDate = "2012-02-27 00:00:00.0";
String TimeZoneIds = TimeZone.getDefault().getID();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
sdf2.setTimeZone(TimeZone.getTimeZone(TimeZoneIds));
try {
Date date = sdf1.parse(strDate);
String strFinalDate = sdf2.format(date);
System.out.println(strFinalDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

In an Oracle DATE column there is no format; the string representation you see when you select max(create_dt)) from profile_details in SQL*Plus, say, is using an implicit format mask from your NLS settings, which appears to be DD-MON-RR in that client.
You JDBC call is applying an explicit format mask, which is the right thing to do if you want Java to treat it as a String, not least because it may have different NLS settings. But your mask doesn't match what you say you want; you're specifying DD-MM-YYYY when you want DD-MON-RR.
But it also looks like you're probably retrieving the value from the JDBC call with a getDate() call, and it's being implicitly cast back to a Java Date object type. If you want to treat it as a Date in Java, then you don't need the to_char in your select, and you need to use Java tools (e.g. SimpleDateFormat as #Andrew Logvinov suggests) to turn it into a String as needed. If you're only ever treating it as a String - for immediate display, say - then use getString() instead, and fix your date format mask in the query.
Edit
If you retrieve the value from JDBC with getDate() and want to see the value as a String in the format you specified, you need to do something like:
Date raw_date;
String string_date;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
raw_date = <resultSet>.getDate(1);
string_date = sdf.format(raw_date);

select to_char(max(CREATE_DT),'dd-MON-yy') from PROFILE_DETAILS;

Related

Convert String to "yyy-MM-dd" format with Date as data type

I'm trying to get the data stored in database by getting the date then populate the table.
List<String> contents = new ArrayList<>();
List<Record> records
try {
Session session = sessionFactory.getCurrentSession();
Query<World> query = null;
query = session.createQuery("from World where date like :dateCont, World.class);
query.setParameter("dateCont", "%" + contents.get(0) + "%");
worlds = query.getResultList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem here is that it gives me an error exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to
class java.util.Date (java.lang.String and java.util.Date are in
module java.base of loader 'bootstrap')
I know what's wrong because the List<String> contents values are string and needed to be converted to Date but I tried so many codes and it doesn't work.
//The following are the codes that I tried but it won't work:
//FIRST
Date date = new SimpleDateFormat("MM/dd/yyyy").parse(contentsStart.get(0));
new SimpleDateFormat("yyyy-MM-dd").format(date);
//---------------------------------------
//SECOND
Date newDate;
DateFormat formatter = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
newDate = (Date) formatter.parse(contentsStart.get(0));
So, is there any way to change the given value to date but it should retains the format "yyyy-MM-dd" and the datatype should be Date.
PS: the format of date in database is "yyyy-MM-dd" also.
Both my date entity field and date from DB is both Date as their
datatype.
Try this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1= (Date) format.parse(yourDate);
You can use like operator only on string (VARCHAR) fields. In the WHERE clause you have to convert your field to string (using format function) in order to be able to use LIKE. So you have to call the convert function (also) IN THE QUERY.
Unfortunately, there are no DATE-functions in EJBQL, so you will have to switch to the native query. For example, for Oracle you can use TO_CHAR like this
SELECT ... WHERE TO_CHAR(date, 'MM/DD/YYYY') LIKE ...
For good performance you will have to add a functional index.
See also http://www.sqlines.com/oracle-to-sql-server/to_char_datetime
One alternative would be to add a new string column date_string, that will contain the formatted representation of your date and use this column with LIKE. But you will have to make absolutely sure, that both dates are always synchronized.

JCalendar - setting date correctly in Java using correct format

I am using the JCalendar from here: http://www.toedter.com/en/jcalendar/
I have used the JDateChooser to set date in a form and import into SqLite in the format yyyy-MM-dd. WhenI try retrieving the date in the same format yyyy-MM-dd from the database with this code:
Date date = rs.getDate(10);
fieldClose.setDate(date); //displays 01-Jan-1970 - I want (2013-01-08), one that is similar in database.
I have looked at stackoverflow, and some similar posts exists, but fails to show recommendations in terms of format yyyy-MM-dd and consideration of jCalender and SQLite so i am having to post this. any ideas how to achieve a date similar to database, in the same format it was inserted and of same type.
I have just tried this:
String date =rs.getString(10);
((JTextField)fieldClose.getDateEditor().getUiComponent()).setText(date);
returns:
2013-05-22 // comes in red line, meaning jDatechooser doesnt recognise it
Use SimpleDateFormat, try this example
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try{
date=sdf.parse(rs.getString(10));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fieldClose.setDate(date);
either you can use SimpleDateFormat in java
or use DATE_FORMAT('ColumnName', "Date Pattern") in Mysql SELECT query.
You can use String.format. Let me help you with the code
Date o = jDateChooser1.getDate(); //Import java.util not java.sql
String x = String.format("%1$ty-%1$tm-%1$td",o);

Java Date Format

I have a table in MySQL server called Caller_List. In this table I have a single date column called call_date whose data type is Date. I have created a web page in which I have a SELECT Box for from_day (where all days 1 to 31 are stored), a SELECT box for month (where all month names from January to December are stored), a SELECT box for year (where all years from 2000 to 2012 are stored. Like I also have a SELECT box for to_day, to_month and to_year.
The problem is when I fetch these day,month and year from java servlet using request.getParameter() method, it is fetched as string data type and stored in variable called from_date and to_date. I concatenate from_day,from_month and from_year and store in the variable called from_date. Also I concatenate to_day,to_month and to_year and store in to_date. I concatenate them in the format year-month-day since MySQL understands this format.
I then pass the following query to retrieve data between these two from_date and two date:
select caller_name,call_date
from Caller_List
where call_date>='"+from_date+"' and call_date<='"+to_date+"'
I also tried the following query but in vain:
select caller_name,call_date
from Caller_List
where call_date between '"+from_date+"' and '"+to_date+"'
I also came to know that I need to convert from_date and to_date to date format before executing the query. But I am a novice in java, I do not know how to do it. Also I want the date in the format year-month-date. I do want to display time with date, please please help me!
If you only want to know how to parse a String to a Date in java, you could simplely use the SimpleDateFormat class.
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
final Date fromDate = dateFormat.parse(from_date);
} catch (ParseException e) {
// ...
}
Assume that your from_date string is looks like 2012-09-16.
And if you want to display a date with time. You can also use the SimpleDateFormat.
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
final String displayDate = dateFormat.format(new Date());
} catch (ParseException e) {
// ...
}
The displayDate should looks like 2012-09-16 20:13:25.
One more thing, you could compare a string type and a date type in MySQL. Just make sure your date string has the pattern "yyyy-mm-dd hh:mm:ss". Of course, you should use the preparedStatement.

Java: unparseable date exception

While trying to transform the date format I get an exception:unparseable date and don't know how to fix this problem.
I am receiving a string which represents an event date and would like to display this date in different format in GUI.
What I was trying to do is the following:
private String modifyDateLayout(String inputDate){
try {
//inputDate = "2010-01-04 01:32:27 UTC";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
Anyway the line
String modifiedDateString = originalDate.toString();
is dummy. I would like to get a date string in the following format:
dd.MM.yyyy HH:mm:ss
and the input String example is the following:
2010-01-04 01:32:27 UTC
Does anyone know how to convert the example date (String) above into a String format dd.MM.yyyy HH:mm:ss?
Thank you!
Edit: I fixed the wrong input date format but still it doesn't work. Above is the pasted method and below is the screen image from debugging session.
alt text http://img683.imageshack.us/img683/193/dateproblem.png
#Update
I ran
String[] timezones = TimeZone.getAvailableIDs();
and there is UTC String in the array. It's a strange problem.
I did a dirty hack that works:
private String modifyDateLayout(String inputDate){
try {
inputDate = inputDate.replace(" UTC", "");
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
But still I would prefer to transform the original input without cutting timezone away.
This code is written for Android phone using JDK 1.6.
What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.
Update: Okay, I did a test:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
This correctly prints:
03.01.2010 21:32:27
(I'm on GMT-4)
Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.
I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.
From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:
String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);
Next step is parse stringDate to Date:
Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);
Note that, parse method throws ParseException

How to convert a string to RegularTimePeriod in java?

I am using Jfreechart. I have the code like this:
TimeSeries t1 = new TimeSeries("EUR/GBP");
t1.add(new Day(4, MonthConstants.JANUARY, 2001), new Double(1.5807));
But I get String from my SQL query. TimeSeries accepts only RegularTimePeriod or TimeSeriesDataItem.
Please let me know how to convert a String into RegularTimePeriod.
Thanks in Advance.
First you can get a Date object by parsing your mysql date string using a SimpleDateFormat, then create your RegularTimePeriod using the constructor with a Date arg.
Basically (assuming mysqlDateStr is your string from mysql query) :
SimpleDateFormat standardDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// (Define your formatter only once, then reuse)
Date myDate = standardDateFormat.parse(mysqlDateStr);
// (you may want to catch a ParseException)
t1.add(new Day(myDate), new Double(1.5807));

Categories