Converting String date to SQL Date - java

I have a string date in the format DD/MM/YY (16/07/13)
How do I convert this string date to SQL Date format (maintaining the same DD/MM/YY format)
for storing in my Oracle DB.. ??

Use a SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String stringWithDate = "16/07/13";
Date theDate = sdf.parse(stringWithDate);
//store theDate variable in your database...
Note that SimpleDateFormat#parse throws ParseException.
UPDATE: Using Java 8 and LocalDate
LocalDate localDate = LocalDate.from(
DateTimeFormatter.ofPattern("dd/MM/yy")
.parse(fecha));
If you need to pass this to java.sql time objects, you can see this answer on How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?

I don't know Java and I'm not super familiar with Oracle, but this may help.
In MS SQL Server I've seen all kinds of bad stuff happen when people try to post stuff using specific date formats. Windows date settings can vary so problems are almost guaranteed. From that point of view your
(maintaining the same DD/MM/YY format)
rings alarm bells
I'm yet to have issues as I usually fall back on handling dates in a "standardised" way.
'yyyymmdd'
select CAST('19900506' AS DATETIME)
is very predictable, so if you want predictable you need the oracle equivalent
it also works for date + time
'yyyymmdd hh:mi:ss.mmm'
select CAST('19900506 01:01:01.000' AS DATETIME)
Oracle/PLSQL will have similar functions that work in an controllable way. Use these functions to save values correctly then your data can be reliably output in whatever format you specify at the time of retrieval

Related

Is there a simple way to change a timestamp value containing seconds and ms to a timestamp value having hours and minutes?

So I have an object ('Task') that has an attribute 'Start Date' which is basically a Timestamp object. So this date is in this format 'YYYY/MM/dd hh:mm:ss:ms'. But for a test case I am authoring, I need this date to be in this format 'YYYY/MM/dd hh:mm'. Also it needs to be a timestamp object as I have to set this value back to the 'Task' object.
I have tried several approaches including the snippet shown below:
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd hh:mm");
if (task.getStartDate() != null) {
String newDate = formatter.format(task.getStartDate());
Date date = formatter.parse(newDate);
task.setStartDate(new Timestamp(date.getTime()));
}
I expected the value of the timestamp to be in the format '2018-12-30 09:54' but it resulted in '2018-12-30 09:54:00.0'. So the questions that I have in mind is:
Is there a way to not consider the seconds and millis in the Timestamp object?
If no, then, is the snippet provided an efficient way to update the Timestamp object?
TL;DR
Avoid the Timestamp class if you can. It’s poorly designed and long outdated.
To answer your questions, no, a Timestamp hasn’t got, as in cannot have a format (the same holds true for its modern replacement, Instant (or LocalDateTime)).
Under all circumstances avoid SimpleDateFormat and Date. The former in particular is notoriously troublesome, and both are long outdated too.
Don’t put a format into your model class
You should not want an Instant nor a Timestamp with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Instant object belongs in your model, so keep your Instant or Timestamp there and never let the user see it directly. I hope that it’s clear to you that 2018-12-30 09:54 and 2018-12-30 09:54:00.0 represent the same value, the same Timestamp. Just like 17, 0017 and 0x11 represent the same integer value. When you adhere to what I said, it will never matter which format the Instant has got.
Whenever the user should see the date and time, this happens in the UI, not in the model. Format it into a String and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Instant into a string for that purpose.
java.time and JDBC 4.2
Also for exchange with your database over JDBC, provided that you’ve got a JDBC 4.2 compliant driver, prefer to use a type from java.time over Timestamp. If the datatype on the database side is timestamp with time zone, very clearly recommended for a timestamp, pass an OffsetDateTime like
OffsetDateTime dateTime = yourInstant.atOffset(ZoneOffset.UTC);
yourPreparedStatement.setObject(4, dateTime);
Use setObject, not setTimestamp. Some drivers accept the Instant directly, without conversion to OffsetDateTime. If on the database side you need a mere timestamp (without time zone), use LocalDateTime in Java instead and pass one to setObject in the same way as above.
PS There are errors in your format pattern string
In a format pattern string, uppercase YYYY is for week based year and only useful with a week number. For year use either uuuu or lowercase yyyy. Similarly lowercase hh is for hour within AM or PM from 01 through 12 and only useful with an AM or PM marker. For hour of day from 00 through 23 you need uppercase HH. These errors will give you incorrect dates and times in most cases. Using the wrong case of format pattern letters is a very common mistake. SimpleDateFormat generally doesn’t mind, it just gives incorrect results. The modern DateTimeFormatter does a somewhat better job of notifying you of such errors.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related questions
Formatting timestamp in Java about getting rid of the .0 decimal on the second of a Timestamp.
timestamp formatting in scala [duplicate] about getting a Timestamp with only date and hour (no minute, second or fraction of second).
java parsing string to date about uppercase Y for year in a format pattern string.
Comparing two times in android about lowercase h for hour of day in a format pattern string.

How to change to display format of datetime received from a database in java

I use this code to change util to sql, but the record happens with seconds and another value after
String insertAttendence = null;
insertAttendence = "INSERT INTO ATTENDANCE (PRSN_ID,DATE,ARRIVAL,DEPART,DATE_ARRIVAL_FROM,DATE_DEPARTURE_TO) VALUES (?,?,?,?,?,?)";
PreparedStatement psAttendence = null;
psAttendence = dbConnection.prepareStatement(insertAttendence);
psAttendence.setInt(1, personIdForGraphics.intValue());
java.sql.Date sqlDate = new java.sql.Date(dates.get(i).getTime());
psAttendence.setDate(2, sqlDate);
In the database it is saved as follows 2019-07-26 11: 53: 18.0, I want it to be saved so 2019-07-26 11:53:18, how to change it?
You don’t want to
You don’t want the datetime in your database to have a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your data model. The value of the datetime belongs in your model, so keep your datetime there and never let the user see it directly. When you adhere to this, it will never matter which format the datetime has got in the database. Whenever the user should see the date, format it into a String and show the string to the user. Similarly if you need a specific format for exchange with another system, format the datetime into a string for that purpose. If the user needs to enter a date and/or time, either accept a string or use a date picker or time picker.
You cannot
As #GuidoG has already said in comments, a datetime is stored in the database in some internal format that we don’t know and shouldn’t care about. It certainly isn’t the 2019-07-26 11: 53: 18.0 that you reported. You may have seen that in some query tool or as a result of retrieving the datetime as a string from your database, I don’t know. It may also be that you can configure your query tool to show you a different format. You can think of the datetime in the database as a date and time of day, nothing more, nothing less.
In short “format” applies only to the string representations of datetimes, not to the datetimes themselves.
java.time and JDBC 4.2
The java.sql.Date class that you were using is poorly designed and long outdated. Also your JDBC driver should treat it as a date without time of day, and most JDBC drivers do (so it’s a bit weird how you got your code to store 2019-07-26 11: 53: 18.0 with non-zero time of day).
Assuming that you want to store a point in time (a timestamp), change your database column to datatype timestamp with time zone and then store an OffsetDateTime into it. I am assuming that dates.get(i).getTime() gives you the milliseconds since the epoch.
OffsetDateTime dateTimeToSave = Instant.ofEpochMilli(dates.get(i).getTime())
.atOffset(ZoneOffset.UTC);
psAttendence.setObject(2, dateTimeToSave);
If you cannot change the datatype, you may store a LocalDateTime into your database column using psAttendence.setObject in the same way, but you will have to make sure yourself that you get a LocalDateTime in the right time zone since the object itself carries neither time zone nor offset. UTC is recommended.
Tutorial link: Oracle tutorial: Date Time explaining how to use java.time.
import java.util.Date;
import java.text.SimpleDateFormat;
public class Test {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-DD hh:mm");
String strDate= formatter.format(date);
System.out.println(strDate);
}
}

Sql timestamp to Java date?

I have a database which is going to have UMT timestamps in standard sql format. How can I pull that data and set a java date object with it?
As far as I know mysql is yyyy-mm-dd hh:mm:ss As for java, the date / time stuff has always eluded me.
If anyone knows of a good library for this I am open to suggestions.
Why don't directly read it as Date
Date date = resultSet.getTimestamp("date_field");
Timestamp timestamp = resultSet.getTimestamp("date_time_field");
See
ResultSet.getTimeStamp()
A Timestamp is a subclass of a Date, which means it is usable everywhere where a Date is. The only difference is, Timestamp is more precise (due to the SQL specification) than Date is.
Just use:
Timestamp t = resultSet.getTimestamp("columnname");
Date d = t;
That having said, there are some benefits of converting the JDBC returned timestamp into a proper Date value, omitting nanoseconds. When you compare a Timestamp and a Date in some remote part of your app, the Timestamp and the Date won't be equal, even though they seem to be "rougly" the same time value. So if this could cause problem, create a new Date instance using only the .getTime() value returned by Timestamp)
More on this in my blog: Timestamp and Date equality when using Hibernate
(even though the blog entry is about Hibernate, it applies to your case as well)

How to refactor my date/time to allow for setting dates for my users based on their zone?

My code currently uses java dates.
Mysql has column datetime.
I want to allow users to set their timezones, and then in my application I will convert the dates to reflect their timezones.
I am using Spring mvc.
How can I do this?
The Datetime type in MySQL does not have timezone associated with it. Instead, by default Connector/J (the MySQL JDBC Driver) gets the date using the server timezone. There was a setting for changing that, but I don't know if it is documented, I had to look through the source to see how it works.
I could save the user's timezone it a different column as VARCHAR, and use that when creating the date objects. If you don't want to change all your data, you can populate the time_zone column with the server default timezone, and then gradually change the timezones for users. Using the following code you can get the UTC Timestamp. The Calendar/Date objects are quite a mess, an you would be better using Joda Time.
ResultSet rs = null;
Date date = rs.getDate("date");
TimeZone userTimeZone = TimeZone.getTimeZone(rs.getString("time_zone"));
Calendar c = Calendar.getInstance(userTimeZone);
c.set(1900 + date.getYear(), date.getMonth(),
date.getDate(), date.getHours(),
date.getMinutes(), date.getSeconds());
//what you are actually interested in
long utcTimestamp = c.getTimeInMillis();
The common strategy is to store date and time information in the database using UTC (+0) and then convert to/from the users time zone preference in the GUI layer.

MySQL timestamp to Java date conversion

How can I convert time in unix timestamp to normal time?
Your question is vague and ambiguous. I'll leave the timezone ambiguity away.
How can I convert time in unix timestamp to normal time?
I suspect that you're somehow obtaining a long or maybe a String value from the DB instead of a Date. In JDBC, you would normally like to use the appropriate methods to obtain the DB-specific datatypes. The MySQL TIMESTAMP datatype can be obtained by ResultSet#getTimestamp() which gives you a java.sql.Timestamp which in turn is a subclass of java.util.Date.
In a nut, the following should do:
Date date = resultSet.getTimestamp("columnname");
To format it further in a human readable format whenever you're going to present it to the enduser, use SimpleDateFormat. Click the link, it contains an overview of all patterns. Here's an example:
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
To do all the other way round, use respectively SimpleDateFormat#parse() and PreparedStatement#setTimestamp().
Unix timestamp is seconds since "epoch". Java's currentTimeMillis are milliseconds since "epoch". You can get a Java Date object with a simple multiplication like this:
Date dateFromUnixTime = new Date( 1000l * unixTime) ;
From there, you can format it using the normal date formatting tools in Java.

Categories

Resources