Java jdbc how to insert current date but formatted into database - java

I am using postgres 9.4(Date Column) as my database and would like to know if it is possible to insert a formatted date into the database using JDBC preparedstatement in the following format (I been searching around and couldn't find anything): Aug-21-2015. This is my code
Calendar calendar = Calendar.getInstance();
java.util.Date today = calendar.getTime();
SimpleDateFormat formatter= new SimpleDateFormat("MM-dd-yyyy");
java.util.Date mydate= formatter.parse(today.toString());
preparedStatement.setDate(2,new java.sql.Date(mydate.getTime()));
needless to say that does not work and I get this error
Unparseable date: "Fri Aug 21 01:17:59 EDT 2015"
again I am trying to get this into Aug-21-2015 , I can successfully execute the code if I only insert like this
Calendar calendar = Calendar.getInstance();
java.util.Date mydate = calendar.getTime();
preparedStatement.setDate(2,new java.sql.Date(mydate.getTime()));
but it is inserted as 8-21-2015, I was thinking of maybe just saving it as 8-21-2015 format and then just parsing all of them but would prefer the 1st option.

Your date pattern is wrong: it must be:
SimpleDateFormat formatter= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
For mor information see the javadoc of SimpleDateFormat

A value in a date column itself is not formatted, it is just a date, if you want to format the date when you're reading it back out of the database, just use one of the date formatting functions.
E.g.
select to_char(your_date_column, 'MON-DD-YYYY') from yourtable

Don't know why you're converting to string and back, but today.toString() is NOT generating a text string that matches MM-dd-yyyy, so formatter.parse(today.toString()) will fail.
If the intent was to remove the time portion, in order to get "today", you can:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(year, month, day);
java.sql.Date today = new java.sql.Date(cal.getTimeInMillis());
Or, with Java 8:
java.sql.Date today = java.sql.Date.valueOf(LocalDate.now());
Date Format
And for your desire the insert a "formatted date", then you are confused. A date column in the database doesn't have a format, it simply stores the date value.
When you query the date column, you get the date value, which can be retrieved in Java using the ResultSet.getDate() method.
When you query the date in a tool, the tool will convert the date to a text value for display. Some tools will allow you to control the date format.
If you otherwise want to control the date format, you can convert the date to a text column in the query, using DBMS specific formatting functions.

Related

Adding 30 days on the value from JDateChooser using Java netbeans

hi all I am working on a form using JDateChooser I want to get the value of date inputted by the user. Is there any ways that after storing the value of date in a variable can I add 30 days from the inputted date? This is my code in passing the date to a string variable:
String dates =((JTextField)date.getDateEditor().getUiComponent()).getText();
my problem is how can I pass the date into a variable where i can be able to add an additional 30 days on it?
please help me really need this for my project .
To manipulate a String with a date value, you first need to convert to a Date using SimpleDateFormat, then you can perform manipulation using a Calendar.
SimpleDateFormat datefmt = new SimpleDateFormat("MM/dd/yyyy"); // Or format you're using
Date date = datefmt.parse(dates);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 30); // Add 30 days
Date futureDate = cal.getTime();
If you need value for insertion into a database, you will of course use PreparedStatement, so you'll need a Timestamp instead:
// From Date
Timestamp futureTimestamp = new Timestamp(futureDate.getTime());
// Directly from Calendar
Timestamp futureTimestamp = new Timestamp(cal.getTimeInMillis());

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Oracle Date Format change to yyyy-MM-dd hh:mm:ss

I have date saletime as 2/25/14 22:06 I want to store it in oracle table in the yyyy-MM-dd hh:mm:ss. So I wrote following java code
Date saleTime = sale.getSaleTime();
logger.info("DateTime is "+saleTime);
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
logger.info("DateTime after Formating "+saleTimeNorm);
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
logger.info("New Format Inserting :"+oracleDate);
sale.setSaleTime(oracleDate);
But this seems to be giving :0014-02-25 22:06:00.0
Any suggestions ?
Your getSaleTime() method somehow regards "14" as a four-digit year, and returns the year 14.
After you have executed getSaleTime(), you already have a Date variable; there is no need (and no use) in converting it to a different output format and re-parsing the result. The Date you get from the calls to format() and parse() will be the same one you started with.
You can create your Timestamp using getTime() on the result of the call to getSaleTime(). That will be correct once you change getSaleTime() so that it returns the date in the correct year.
Something must be wrong in your sale.getSaleTime() method. Because the following code working as needed.
Date saleTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
System.out.println(oracleDate);
//2014-05-13 03:58:53.0

Date Class error in java

I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);

I get ever a false date in SqLite

I save a Date and this is ever 1698-19-20 and not 2012-4-12. Here one sees the error?
Date saved as Integer.
calculated with the calculator:
1334262386066 millisecond
42.309182713914 year + 1970 Year = ~2012
Code:
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
calendarEntity.setDate(date);
sqlite query:
SELECT strftime('%Y-%m-%d',DATE) FROM CALENDAR_ENTITY
Table:
CREATE TABLE 'CALENDAR_ENTITY' ('_id' INTEGER PRIMARY KEY ,'TITLE' TEXT,'NOTICE' TEXT,'DATE' INTEGER,'BABY_ID' INTEGER NOT NULL )
If you can use this return long like this I think your problem will solved itself.
Date date = new Date(1334262386066l);
This will return what you expected. And this is what it prints Thu Apr 12 23:26:26 EEST 2012
The problem is that strftime function expects the date as text in one of these formats:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDD.DDDD
You are storing the date as integer which strftime function can't handle.
More details about SQLite datetime functions here (or here, page 80).

Categories

Resources