How to convert a string to RegularTimePeriod in java? - 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));

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.

How do I pass a Date as SQL parameter in Java without losing the time part? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps

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.

different date format in java after fetching from oracle

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;

How to convert a string into TimeSeriesDataItem

I am using Jfreechart. I have the following code:
TimeSeries t1 = new TimeSeries("EUR/GBP");
t1.add(new TimeSeriesDataItem....);
But my SQL query gives date in String format & value in Double. I want to use TimeSeriesDataItem. Please let me know how to convert my String into TimeSeriesDataItem.
Please let me know how to add my Double value to TimeSeriesDataItem.
Thanks in Advance.
1) convert your date from String to java.util.Date
2) wrap this Date instance using one of the classes extending RegularTimePeriod.
eg. RegularTimePeriod p = new Day (myDate)
3) TimeSeriesDataItem t = new TimeSeriesDataItem (p, a_numeric_value)
What is the format of the date string?
Assuming the format is DD-MM-YY.
First convert the string to a Date object.
String date_S = "04-06-16"; //your date from SQL
Date date;
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yy");
try {
date = sdf2.parse(dateS);
} catch (ParseException e) {
e.printStackTrace();
}
TimeSeries add takes RegularTimePeriod and Double as arguments
So create a RegularTimePeriod object and add it to the series.
RegularTimePeriod rtp = new Date(date);
TimeSeries t1 = new TimeSeries("EUR/GBP");
TimeSeriesDataItem tsdi = new TimeSeriesDataItem(rtp , Double);
t1.add(tsdi);

Categories