Converting a date a string to java.sql.Date format - java

I'm having an issue while trying to insert a date into an SQL server using Java:
//final String input = "20120823151034";
final String input = "06282013143533";
final DateFormat df = new SimpleDateFormat("MMddyyyyHHmmss");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
//c.add(Calendar.MILLISECOND, 1);
String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());
System.out.println(sqltDate);
Here, I'm expecting the complete string being output as the year, month, day, hour, minutes, and seconds to be inserted into SQL server, but I'm only getting the year, month, and the date. What should I do to insert the date and the time into the database?

check your DATA type in database either it should be Timestamp or Datetimefor this purpose you can use database function NOW() for current date and time.and convert your date into timestamp
Timestamp timestamp = new Timestamp(new Date().getTime());
and insert this timestamp into database

java.sql.Date can be used to store only the year, month and day of the month. It can't be used to store the time of the day.
In order to store time, you would have to use Timestamp. In your above code, replace
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());
by
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());
The above changes will make things work fine.

Related

How can we convert Timestamp datatype in Java to UTC timezone in JPA entity Java?

We are using PO class to represent the sql DB and using Java JPA entity.In that class, we have one column as a field currentTime with Timestamp datatype and #version annotation from JPA.
#Version
private Timestamp currentTime;
whenever the entity gets updated, currentTime is updated with the latest time.
currentTime = new Timestamp(0); //this will create the new timestamp with current time.
but it’s currently taking the time from the server. I want to convert this time to UTC format before saving it to DB.
Anyone can help how can I convert the time to UTC time?
I had a similar problem when I needed to parse the time from server but I needed to convert this time to UTC format before storing this information int MySQL DB. This was my solution:
Instant dateConverted = LocalDateTime
.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH))
.atZone(ZoneId.of("Europe/Bratislava")).toInstant();
long epochTime = dateConverted.toEpochMilli() / 1000L;
Where dateTime is a String variable containing the date and time from server
And I have used DateTimeFormatter to format my time to appropriate format.
At the end I have added the zoneID of my timeZone and converted it to Instant
And at the end I have converted to seconds
Try below code,
currentTime = Timestamp.valueOf(LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String localTime = sdf.format(new Date(your_time_stamp));
Date date = new Date();
try {
date = sdf.parse(localTime);//get local date
} catch (ParseException e) {
e.printStackTrace();
}

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.

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());

DateTime convertion in java

I have a date get saved in the database in IST format.
Date nowDate = new Date();
Date dateBefore = new Date(nowDate.getTime() - 7* 24 * 3600 * 1000);
System.out.println("Datebefore-->"+dateBefore);
Here in the above code dateBefore is get saved in the database.
From the database I am taking the data long value and I have to convert this into Google DateTime
Date dateBefore12 = new Date(longvalue);
com.google.api.client.util.DateTime dd = new DateTime(dateBefore12, TimeZone.getTimeZone("UTC"));
Now for example the output will be in the 2014-07-17T05:23:28.857Z which I have to pass to the Google You tube API.
Now from the response I will take Google DateTime, let say 2014-07-17T05:23:28.857Z which I have to increment the 1 minute and then convert it into long and save into db.
Convert the google DateTime to long.
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = dd.toString();
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
cal.add(Calendar.MINUTE,1);
Date time = cal.getTime();
long longvalue1 =cal.getTimeInMillis();
Now I will saved the data and try to retrieve it. It gives me back 2014-07-16T23:54:28.857Z.
But I need the save date value which I have increment by one minute in the format of google DateTime.
SimpleDateFormat also uses a time zone, due to an internal Calendar object, which defaults to the local time zone. If you don't want to use that default time zone, then before you call the format's parse() method, you should call setTimeZone() on it:
f.setTimeZone(utc);

Formatting timestamp in 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();

Categories

Resources