How to save current date and time to database using java? - java

I am using the following code to get the current date and time, but the output is not what I am expecting and I cant save it into database.
Output >> current: Tue Mar 05 09:58:26 EST 2013
Expected output >> current: 2013-03-05 9:58:26
.....{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
System.out.println("current: " +parseFormat.parse(dateFormat.format(date)));
return parseFormat.parse(dateFormat.format(date));
} catch (ParseException ex) {
Logger.getLogger(ConstructionModel.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}
......
ps.setDate(....) <<< failed
Database
name type
mydate Date

You don't need to parse before formatting:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String frmtdDate = dateFormat.format(date);
System.out.println("frmtdDate: " + frmtdDate);
However, if you are trying to fit the date into some DB statement, you should not do it in the form of text, instead use one of the JDBC setters that utilize java.sql.Date or java.sql.Timestamp

You need to use sql timestamp for saving to the database. Convert your java.util.Date to java.sql.Timestamp:
ps.setTimestamp(new java.sql.Timestamp(myDate.getTime()));

format takes a Date and returns a formatted String. parse takes a formatted String and returns a Date object. When you do parseFormat.parse(dateFormat.format(date)) you are converting Date to String and to Date again. The value that is printed is the default representation provided by Date.toString() instead of the formatted string.
System.out.println("current: " +dateFormat.format(date));

Related

issue in converting the date from string to date type

below is the code I have used to add the number of days to the existing date..which gave me string output and I want that to be converted to Date format again...I have tried formating but it gave the out put -->
Date date = sdf.parse(dt);
sysout (date ) --giving me -- Mon May 05 00:00:00 PDT 2008
but I want it as YYYY-MM/DD
sdf.format(date) --Gives me 2008-05-05 which I am looking but it is a string object...but I want this to be converted to DATE type
String dt = "2008-01-01"; // Start date
System.out.println("start date "+dt);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 125); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("c.getTime() "+c.getTime());
System.out.println("end date "+dt);
Date date = sdf.parse(dt);
System.out.println("last but one date in DATE form -->" +date);
System.out.println("last formatted date in string form "+sdf.format(date));
You created the format right.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
but you are using it incorrectly. you should use
sdf.format(your_unformated_date);
Here is a sample code that will convert date from String to Date type using SimpleDateFormat Class:
public static void convert()
{
String str="10:25:35";
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(str));
}

Data truncation: Incorrect datetime value: '' for column 'date' at row 1

My application is getting this error:
Data truncation: Incorrect datetime value: '2-24-2015' for column 'POrder_Date' at row 1
I have MySQL connector java v-5.1.7
java.util.Date date = new java.util.Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
String date1, mon, datex, year, yearx, currentDate;
int d, d1;
following code is in my class,s constructor:
date1=df.format(date);
d=date1.indexOf('/');
mon=date1.substring(0,d);
d1=date1.lastIndexOf('/');
datex=date1.substring(d+1,d1);
yearx=date1.substring(d1+1);
year="20"+yearx;
currentDate=mon+"-"+datex+"-"+year;
System.out.println("current date "+currentDate);
mysql default date format "yyyy-mm-dd".change date format then store .may be it will work.
java.util.Date date = new java.util.Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
String date1,mon,datex,year,yearx,currentDate;
int d,d1;
date1=df.format(date);
d=date1.indexOf('/');
mon=date1.substring(0,d);
d1=date1.lastIndexOf('/');
datex=date1.substring(d+1,d1);
yearx=date1.substring(d1+1);
year="20"+yearx;
currentDate=mon+"-"+datex+"-"+year;
System.out.println("current date "+currentDate);
//change currentdate format MM-dd-yyyy into yyyy-MM-dd
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date convertedCurrentDate = sdf.parse(currentDate);
System.out.println(new SimpleDateFormat("yyyy-MM- dd").format(convertedCurrentDate));
} catch (ParseException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
check print date format like(2015-05-25).
You have two choices here:
Either use updateDate() where you presently use rs.updateString(2,podate). Pass a Date object to updateDate().
Or change your internal date formatting throughout to comply with the ISO yyyy-mm-dd standard.

How to get a Date object from String

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
Date d = (Date)formatter.parse(dateTime);
System.out.println("date in controller "+d);
I get the output as
date in controller Mon Dec 31 16:04:57 IST 2012
Please suggest a method to output the date in MM/dd/yyyy HH:mm:ss format.
Need the output in date format and not as string so as to store the output in datetime field in mysql db
Need the output in date format and not as string so as to store the output in datetime field in mysql db
After the statement
Date d = (Date)formatter.parse(dateTime);
java.sql.Date sqldate = new java.sql.Date(d.getTime())
you have got a java.util.Date object and you can store it as it is in mysql DB (column type : datetime).
However, when you are printing d, it defaults to the .toString() implementation. I think you expected some output like Date# but the toString printed in user readable format thats why the confusion.
You are using d an object of Date class, so its toString method is called that gives the output as Mon Dec 31 16:04:57 IST 2012.
If you want to display it in the format that you have specified in your SimpleDateFormat then try using this :
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
Date d = (Date)formatter.parse(dateTime);
System.out.println("date in controller "+ formatter.format(d));
Don't see why the single-qoutes (') are used in the format-string and you also need to catch ParseException:
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d = new Date();
try {
d = (Date)formatter.parse("12/31/2012 12:13:14");
} catch(ParseException pex) { System.out.println(pex.getMessage()); }
// convert the date into java.sql.Date
java.sql.Date sqldate = new java.sql.Date(d.getTime());
// then put it in the database, something like this:
//resultSet.updateDate("myDateTimeField", sqldate);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
System.out.println("date in controller"+ df.format(d));
Try using format instead of parse.
Date date = new Date();
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date) );

Get time from entire date

I have to get time from entire date
e.g. time=11:00:00 from date 2012-09-01 11:00:00.0
I tried following snippet but getting error Error : Unparseable date: "2012-9-1.13.30. 0. 0"
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = inputFormat.parse(iResultSet1.getString(i));
DateFormat outputFormat = new SimpleDateFormat("hh:mm:ss");
String outputString = outputFormat.format(date);
Edit: Now I am getting only date instead I want only time
if (iResultSet1.getDate(i) != null) {
Date date = iResultSet1.getDate(i);
System.out.println("date-->" + date);
// Format date into output format
DateFormat outputFormat = new SimpleDateFormat(
"HH:mm:ss");
String outputString = outputFormat.format(date);
// System.out.println("date1-->"+date1);
I wil suggest, in this case rather doing parsing and manipulation in java change your SQL to format and return only date as
Example
SELECT TIME_FORMAT(NOW(), '%H:%i:%s');
You are probably retrieving your date from the database (iResultSet1.getString(i)) and the problem is that you're getting wrong format, i.e. 2012-9-1.13.30. 0. 0. Either change the date format in the database or use:
Date date = iResultSet1.getDate(i);
instead of
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = inputFormat.parse(iResultSet1.getString(i));

Retreving date from Hibernate TImestamp

I have a field with temporal type as Timestamp to save both date and time to the database.
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date", nullable=false)
private Date date;
But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp.
SimplDateFormat sd = new SimpleDateFormat("MM/dd/yyyy");
return sd.parse(date.toString());
So how do I retrieve just date from Hibernate Timestamp? Thanks
Just format the date object. The toString method isn't guaranteed to give you a string in a format that can then be parsed.
String dateStr = sd.format(date);
That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date.
Date fancyNancy = sd.parse(dateStr);
* EDIT *
Run this code and verify it prints out the day, month and year with no time.
try {
Date d = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Date: " + d);
System.out.println("Formatted Date: " + df.parse(df.format(d)));
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources