Formatting timestamp in Java - java

I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x
How do you get rid of the .x part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.

Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.
You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime)
//will print without showing the .x part
String currentTimeFromTimestamp = df.format(currentTime);
Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:
Timestamp timestamp = new Timestamp(new Date().getTime());

You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.

The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();

Related

Get Now Date and Time

I'm using JPA and I want to store the date in this format dd/MM/yyyy HH:mm:ss
So I create a function
public static String getNowDate() {
Date date = new Date();
final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return sdf.format(date);
}
The problem is that this returns a String and I need a date.
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
How do I make this work so I can save date and time exactly like that?
I know a easy solution is to declare creationDate as String. Is this too bad?
There is a problem with the premise to your question. Ideally, your current timestamp will be stored in a SQL database, in some sort of date column, and not as text. Since you are using JPA, backed by JDBC, you should just be inserting a date type. So, something like the following should work:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// or maybe just
Date now = new Date();
Then, just let JPA worry about how to martial the current timestamp into your database table. If you really need to format your timestamp as shown, then worry about this in your Java code somewhere.

Mapping Date and Time to MySQL

I have created a table in MySQL as :
CREATE TABLE scheduled(sid INT,id INT,tweet VARCHAR(255),sdate DATE,
stime TIME,PRIMARY KEY(sid),FOREIGN KEY(id) REFERENCES usercred(id));
I receive both Date and Time from the HTML input field. Date received from the HTML field looks like :
4/30/2014
How can I map this in Java ? After receiving both Date and Time and after mapping them correctly , I will commit the transaction or will update the table/entry.
could use the parse() method in the SimpleDateFormat object:
SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy");
String dateInString = "4-30-1982"";
Date date = sdf.parse(dateInString);
System.out.println(date);
In JDBC-layer inside PreparedStatement or ResultSet you work with the mapping java.sql.Date (for SQL-DATE) and java.sql.Time (for SQL-TIME). Then you can wrap both types like:
java.sql.Date sqlDate = ...; // from ResultSet
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
String htmlFormat = df.format(sqlDate);
And in reverse:
String htmlFormat = ...;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
java.util.Date d = df.parse(htmlFormat);
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
// use result in PreparedStatement for INSERT or UPDATE
Attention: Both approaches use the standard timezone of the server where this code is running. In case of doubt you should probably set the timezone UTC. Similar code for the TIME-part.

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

how to convert datetime to timestamp in java

forum member
I am having one problem with date time in java. Actually I am receiving the startdate in format 2012-02-27T01:10:10 and I want to insert the received date to my database having datetime datatype.
Actually I tried to convert the startdate received to datetime by below code
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Date endD = sdf.format(eDate);
but with the above code only date gets added to my database like 2012-02-27 00:00:00
I want to add the time also to my database but when I change the SimpleDateFormat to SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); nothing works.
please suggest me some solution I can apply so my time also gets added to database. I am using Hibernate JPA as my persistence layer.
SimpleDateFormat's format() method doesn't return a Date type.
try this:
Date startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(sDate);
Try this,
yyyy-MM-dd'T'HH:mm:ss
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Timestamp startTime = new Timestamp(startD.getTime());
Date endD = sdf.format(eDate);
Timestamp endTime = new Timestamp(endD.getTime());
Of course only the date is parsed, since the pattern you provided to the SimpleDateFormat constructor only contains the date part! Add the time part to it and it will parse the time too just fine.
you can try like this....
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

SimpleDateFormat String

I have this code block where argument to dateFormat.format will always be a string thats why I did .toString() here. I am getting error "Cannot format given Object as a Date".
Is there any way to do this ? Note that string is coming from database I used new Date() as a sample here.
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormat.format(new Date().toString());
DateFormat#format accepts a Date, not a string.
Use
String sCertDate = dateFormat.format(new Date());
If you have a string coming from the database that is a specific format and you want to convert into a date, you should use the parse method.
#Sonesh - Let us assume you have a string in the database that happens to represent a Date ( might be better to store the object in the database as dates? ) , then you would first parse it to the format you wanted and then format it to the string format you wanted.
// Assumes your date is stored in db with format 08/01/2011
SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = dateFormatOfStringInDB.parse(yourDBString);
SimpleDateFormat dateFormatYouWant = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormatYouWant.format(d1);
There are two applications of SimpleDateFormat:
parse a string - when you have a date represented as string, and you want to get the corresponding Date object. Then use dateFormat.parse(string)
format a date - when you have a Date object and you want to format it in a specific way (usually in order to show it to a user). In that case use dateFormat.format(date)
The two methods are reciprocal - one takes a date and returns a string, and the other takes a string and returns a date.
For your particular case, perhaps you need .parse(..). But note that every 'self-respecting' database driver should have an option to return a Date rather than some string representation. If you happen to be storing dates as string in the DB - don't do that. Use the native date type.
If you need to read a Date with one String format and output it to another String format, you need 2 formatters, for example:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String output = outputFormat.format(inputFormat.parse(input));

Categories

Resources