Mysql date from java

java.sql.Date, java.sql.Time, and java.sql.Timestamp

Most of database support three forms of datetime fields which are DATE, TIME and TIMESTAMP. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. These three are:

  • java.sql.Date represents SQL DATE, stores years, months and days without time components. java.sql.Date is disregarding timezones.
  • java.sql.Time represents SQL TIME and only contains information about hour, minutes, seconds and milliseconds without date component.
  • java.sql.Timestamp represents SQL TIMESTAMP which contains both Date and Time information to the nanoseconds precision.

Let’s check below table referring to top 5 databases (not in the order) datetime data types:

Database SQL DATE SQL TIME SQL TIMESTAMP Source
MySQL / MariaDB DATE
DATETIME
TIME TIMESTAMP Link
Link
PostgreSQL DATE TIME
TIME WITH TIME ZONE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
Link
Oracle DATE TIMESTAMP
TIMESTAMP WITH TIME ZONE
TIMESTAMP WITH LOCAL TIME ZONE
Link
Microsoft SQL Server DATE
SMALLDATETIME
DATETIME
DATETIME2
DATETIMEOFFSET
TIME Link
IBM Db2 DATE TIME TIMESTAMP Link

I putting the source, my reference in the right most column. Correct me if I’m wrong

Working With JDBC Classes

Which class to choose is depends on the SQL type of the field. PreparedStatement has setters for all three values, setDate() for java.sql.Date, setTime() for java.sql.Time and setTimestamp() for java.sql.Timestamp.

Let’s down to example, we create a test table in our database. For this article, I’ll use MySQL.

CREATE TABLE test_datetime ( dtm_date DATE, dtm_time TIME, dtm_timestamp TIMESTAMP, obj_date DATE, obj_time TIME, obj_timestamp TIMESTAMP );

And then we insert current date/time (get via new java.util.Date()) into the date field of an SQL database table.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class SqlDateTimeInsertExample < public static void main(String[] args) throws Exception < // (1) connect to mysql database String url = "jdbc:mysql://localhost/coffeehouse?serverTimezone=Asia/Singapore"; Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection(url, "barista", "cappuccino")) < // (2) set java.sql.Date, Time, and Timestamp with current Date (and time) java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); java.sql.Time sqlTime = new java.sql.Time(utilDate.getTime()); java.sql.Timestamp sqlTS = new java.sql.Timestamp(utilDate.getTime()); // (3) insert java.sql.Date, Time and Timestamp (including objects) to DB String sql = "INSERT INTO test_datetime(" + "dtm_date, dtm_time, dtm_timestamp," + "obj_date, obj_time, obj_timestamp) VALUES (. )"; try (PreparedStatement pst = conn.prepareStatement(sql)) < pst.setDate(1, sqlDate); pst.setTime(2, sqlTime); pst.setTimestamp(3, sqlTS); pst.setObject(4, utilDate); pst.setObject(5, utilDate); pst.setObject(6, utilDate); // (4) execute update pst.executeUpdate(); >> > > 

As in above example, with setObject(int parameterIndex , x Object); we can just give a util.Date to the last three parameters which accept it without problem (this is also happen in another JDBC driver, not only MySQL). But to just use setObject(. ) lazily can cause some problem, including data (or part of data) loss.

Читайте также:  Redirect from html file

Note: The URL suffix ?serverTimezone=Asia/Singapore is to suppress: Exception in thread «main» java.sql.SQLException: The server time zone value ‘Malay Peninsula Standard Time’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

(Can you see the typo in above MySQL JDBC error message? :p )

Connect to mysql to confirm the result:

$ mysql -u barista -p Enter password: ********** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 Server version: 5.5.27 MySQL Community Server (GPL) mysql> connect coffeehouse Connection id: 10 Current database: coffeehouse mysql> select * from test_datetime; +------------+----------+---------------------+------------+----------+---------------------+ | dtm_date | dtm_time | dtm_timestamp | obj_date | obj_time | obj_timestamp | +------------+----------+---------------------+------------+----------+---------------------+ | 2019-08-15 | 15:48:19 | 2019-08-15 15:48:19 | 2019-08-15 | 15:48:19 | 2019-08-15 15:48:19 | +------------+----------+---------------------+------------+----------+---------------------+ 1 row in set (0.00 sec)

Liked this Tutorial? Share it on Social media!

Источник

How to convert java.util.Date to Mysql Date Format

So, there is a need to convert the java’s default Date format to Mysql’s date format. The conversion can be done at the database level (through various mysql functions) or at the program level through some java code. We will discuss only the latter part.

Java provides a class called SimpleDateFormat available in java.text package which allows for formatting (date -> text) through format() method and parsing (text -> date) through parse() method.

Here, we will convert the today’s date from java Date object to mysql date format.

2. Create a SimpleDateFormat object by using the constructor,

public SimpleDateFormat(String pattern)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

Parameters:
pattern – the pattern describing the date and time format

String pattern = "yyyy-MM-dd"; SimpleDateFormat formatter = new SimpleDateFormat(pattern);

3. Now use the format() method to convert the date object to text format provided in the pattern.

String mysqlDateString = formatter.format(now);
import java.text.SimpleDateFormat; import java.util.Date; public class JavaToMysqlDate < public static void main(String[] args) < Date now = new Date(); String pattern = "yyyy-MM-dd"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); String mysqlDateString = formatter.format(now); System.out.println("Java's Default Date Format: " + now); System.out.println("Mysql's Default Date Format: " + mysqlDateString); >>

The following pattern letters are defined in SimpleDateFormat.

Letter Date or Time Component Examples
G Era designator AD
y Year 1996; 96
Y Week year 2009; 09
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day name in week Tuesday; Tue
u Day number of week (1 = Monday, …, 7 = Sunday) 1
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
X Time zone -08; -0800; -08:00

So for Mysql DateTime format, you can use the pattern “yyyy-MM-dd HH:mm:ss”

For converting date in String format to Date object, refer this tutorial.

Источник

Convert java.util.Date to java.sql.Date

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Also, the Jet Profiler team have created a 10% discount for us here, which is cool to see. The code to use during checkout is BAELSPECIAL1.

Источник

Оцените статью