Java Advanced Date Concept (dedicated to brothers who want to internationalize time and SQL time)

Source: Internet
Author: User
Tags date format getdate getmessage sql string time and date oracle database
Concept | advanced
Java Advanced Date Concepts                  





If your Java program displays time and date to users in different time zones or different countries, you need to understand some of the more advanced aspects of the Java date class



The classes discussed in this article will contain Java.text.DateFormat, as well as Java.util.TimeZone and java.util.Locate. We will also discuss how to use a java.util.Date subclass Java.sql.Date to extract and save Java Date data from an Oracle database.
areas of the problem
Before we internationalize our date data, we need to learn more about the Locale class, which is Java.util.Locale. An instance of the locale class typically contains country and language information. Each of these sections is made up of two-character strings based on national code ISO-3166 and Language code ISO-639 developed by the International Organization for Standardization (ISO).
Let's create two locale instances, one of which corresponds to American English while the other corresponds to French French. See Table A.
Table A


Import Java.util.Locale;

public class DateExample6 {

public static void Main (string[] args) {
Create a locale for the 中文版 language in the US.
Locale Localeen = new Locale ("en", "US");

System.out.println ("Display Name:" +
Localeen.getdisplayname ());
System.out.println ("Country:" + localeen.getcountry ());
System.out.println ("Language:" + localeen.getlanguage ());

Create a locale for the French language in France.
Locale LOCALEFR = new Locale ("fr", "fr");
System.out.println ("\ndisplay Name:" +
Localefr.getdisplayname ());
System.out.println ("Country:" + localefr.getcountry ());
System.out.println ("Language:" + localefr.getlanguage ());

Display the english-us locale in French
System.out.println ("\nen Display Name in French:" +
Localeen.getdisplayname (LOCALEFR));
}
}
In this example, we use the GetDisplayName method to display a more readable text of the locale. You should also notice that we passed the French locale object at the same time we called GetDisplayName on the Chinese locale object when we called GetDisplayName the last time. This allows us to select the language in which to display the locale object, and let us display the contents of the French locale object in English. The following is the output of this example:
Display name:english (United States)
Country:us
Language:en
Display Name:french (France)
Country:fr
Language:fr
En Display Name in French:anglais (États-unis)
date formatting for multiple geographies
Using the Java.util.Locale and Java.text.DateFormat classes, we can format date data to show it to users in another region, such as France. The example in table B creates a full date formatter for both English and French.
Table B


Import Java.util.Locale;
Import Java.util.Date;
Import Java.text.DateFormat;

public class DateExample7 {

public static void Main (string[] args) {
Get the current system date and time.
Date date = new Date ();

Get a France locale using a locale constant.
Locale localefr = locale.france;

Create an english/us locale using the constructor.
Locale Localeen = new Locale ("en", "US");

Get a date formatter for display in France.
DateFormat FULLDATEFORMATFR =
Dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full,
LOCALEFR);

Get a date formatter for display in the U.S.
DateFormat Fulldateformaten =
Dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full,
Localeen);

System.out.println ("Locale:" + localefr.getdisplayname ());
System.out.println (Fulldateformatfr.format (date));
System.out.println ("Locale:" + localeen.getdisplayname ());
System.out.println (Fulldateformaten.format (date));
}
}
The output of this example is:
Locale:french (France)
Vendredi 5 octobre 2001 H gmt-04:00
Locale:english (United States)
Friday, October 5, 2001 9:05:54 PM EDT
Note that this output includes time zone information: gmt-04:00 and PM EDT. This time zone is captured in the time zone settings of the human system. As you can see, the date is displayed in the format that the user in that area expects. Let's wait and see the concept of the time zone.

Time Zone
The TimeZone class, the instance of the Java.util.TimeZone class, contains a time zone offset in microseconds compared to Greenwich Mean Time (GMT), and it also handles daylight savings


。 To get a list of all the supported Timezone.getavailableids, you can use the method, which returns an array of strings containing all the incoming IDs. For more details on the TimeZone class, refer to Sun's web site.
To demonstrate this concept, we will create three time zone objects. The first object will use Getdefault to return the time zone data from the system clock, and the second and third objects will pass in a time zone string ID. See the Code in Table C.
Table C


Import Java.util.TimeZone;
Import Java.util.Date;
Import Java.text.DateFormat;
Import Java.util.Locale;

public class DateExample8 {

public static void Main (string[] args) {
Get the system time zone.
TimeZone TIMEZONEFL = Timezone.getdefault ();
System.out.println ("\ n" + timezonefl.getdisplayname ());
System.out.println ("Rawoffset:" + timezonefl.getrawoffset ());
System.out.println ("Uses Daylight Saving:" + timezonefl.usedaylighttime ());

TimeZone Timezonelondon = Timezone.gettimezone ("Europe/london");
System.out.println ("\ n" + timezonelondon.getdisplayname ());
System.out.println ("Rawoffset:" + timezonelondon.getrawoffset ());
System.out.println ("Uses Daylight Saving:" + timezonelondon.usedaylighttime ());

Candles Imezone Timezoneparis = Timezone.gettimezone ("Europe/paris");
System.out.println ("\ n" + timezoneparis.getdisplayname ());
System.out.println ("Rawoffset:" + timezoneparis.getrawoffset ());
System.out.println ("Uses Daylight Saving:" + timezoneparis.usedaylighttime ());
}
}
Its output is as follows:
Eastern Standard Time
Rawoffset:-18000000
Uses Daylight Saving:true
gmt+00:00
rawoffset:0
Uses Daylight Saving:true

European Standard Time
rawoffset:3600000
Uses Daylight Saving:true
As you can see, the TimeZone object gives us the original offset, which is the microsecond difference from GMT, and also tells us if the time zone uses daylight savings. With this information, we can continue to combine time zone objects and date formatters in other time zones and other languages.
times of internationalization show time zone conversions
Let's look at an example of a combination of internationalized display, time zone, and date formatting. Table D shows the current full date and time for a company with offices in Miami and Paris. For the Miami office, we will display the full date and time in English in each office. For the office in Paris, we will display the full current date and time in French.
Table D


Import Java.util.TimeZone;
Import Java.util.Date;
Import Java.util.Locale;
Import Java.text.DateFormat;

public class DateExample9 {

public static void Main (string[] args) {
Locale localeen = locale.us;
Locale localefrance = locale.france;

TimeZone Timezonemiami = Timezone.getdefault ();
TimeZone Timezoneparis = Timezone.gettimezone ("Europe/paris");

DateFormat dateformatter = dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full,
Localeen);
DateFormat Dateformatterparis = dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full,
Localefrance);

Date curdate = new Date ();

System.out.println ("Display for Miami office.");
Print the Miami time zone display name in 中文版
System.out.println (Timezonemiami.getdisplayname (Localeen));
Set the time zone of the ' Dateformatter to Miami time zone.
Dateformatter.settimezone (Timezonemiami);
Print the formatted date.
System.out.println (Dateformatter.format (curdate));

Set the time zone of the "date formatter to Paris" time zone.
Dateformatter.settimezone (Timezoneparis);
Print the Paris time zone display name in 中文版.
System.out.println (Timezoneparis.getdisplayname (Localeen));
Print the Paris time in 中文版.
System.out.println (Dateformatter.format (curdate));

System.out.println ("\ndisplay for Paris office.");
Print the Miami time zone display name in French
System.out.println (Timezonemiami.getdisplayname (localefrance));
Set the timezone of the
Dateformatterparis to Miami time zone.
Dateformatterparis.settimezone (Timezonemiami);
Print the formatted date in French.
燬 ystem.out.println (Dateformatterparis.format (curdate));

Set the timezone of the date formatter to Paris time zone.
Dateformatterparis.settimezone (Timezoneparis);
Print the Paris time zone display name in French.
System.out.println (Timezoneparis.getdisplayname (localefrance));
Print the Paris time in French.
System.out.println (Dateformatterparis.format (curdate));
}
}
The output of this example is:
Display for Miami Office.
Eastern Standard Time
Friday, October 5, 2001 10:28:02 PM EDT
European Standard Time
Saturday, October 6, 2001 4:28:02 AM CEST
Display for Paris Office.
gmt-05:00
Vendredi 5 octobre 2001 gmt-04:00
gmt+01:00
Samedi 6 octobre 2001 H gmt+02:00



Save and extract date data in an SQL database
The next class we're going to use is java.sql.Date, which is a subclass of Java.util.Date but it uses the Java Database Connectivity (JDBC) method


。 Let's take a look at a simple Oracle database with a single form--last_access, created with the following SQL:
CREATE TABLE Last_access (
Last_hit Date
);
This form has only one record and is created with the following insert statement:
INSERT into last_access values (sysdate);
Table E shows how to modify and extract the Last_hit database domain.
Table E


Import java.sql.*;
Import Java.text.DateFormat;
Import Java.util.Date;

public class DateExample10 {

public static void Main (string[] args) {
Get a full date formatter.
DateFormat dateformatter = dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full);
Get the system date and time.
Java.util.Date utildate = new Date ();
Convert it to Java.sql.Date
Java.sql.Date Date = new Java.sql.Date (Utildate.gettime ());
Display the date before storing.
System.out.println (Dateformatter.format (date));
Save the date to the database.
Setlasthit (date);
Get the date from the database.
Date Datefromdb = Getlasthit ();
Display the date from the database.
System.out.println (Dateformatter.format (Datefromdb));
}

public static void Setlasthit (Java.sql.Date Date) {

try {
Load the class.
Class.forName ("Oracle.jdbc.driver.OracleDriver");
Get a connection.
Hot onnection connection = Drivermanager.getconnection (
Database URL
"Jdbc:oracle:thin: @localhost: 1521:buzz2",
"Web_site",//Username
"Web_site"); Password
try {
/Get a prepared statement fromthe connection
Specifying the update SQL.
PreparedStatement PS = connection.preparestatement (
"Update last_access set last_hit=");
try {
/Set the date letting JDBC to the work of
Formatting the SQL appropriately.
Ps.setdate (1, date);
Execute the UPDATE statement.
int irowsupdated = Ps.executeupdate ();
System.out.println ("Rows Updated:" + irowsupdated);
finally {
Ps.close ();
}
finally {
Connection.close ();
}
catch (Exception ex) {
System.out.println ("Error:" + ex.getmessage ());
}
}

public static Java.sql.Date Getlasthit () {
Java.sql.Date returndate = null;

try {
Load the driver class.
Class.forName ("Oracle.jdbc.driver.OracleDriver");
Get the connection.
Connection Connection = drivermanager.getconnection (
"Jdbc:oracle:thin: @localhost: 1521:buzz2",
"Web_site", "Web_site");
try {
/Get the prepared statement specifying the
Select SQL.
PreparedStatement PS = connection.preparestatement (
"Select Last_hit from last_access");
try {
Execute the SQL and get the ResultSet object.
ResultSet rs = Ps.executequery ();
try {
Retreive the record.
if (Rs.next ()) {
Return to the last hit date.
Returndate = Rs.getdate ("Last_hit");
System.out.println (
"Successfully retrieved last hit");
} else {
燬 ystem.out.println ("Did not to last hit.");
}
}
finally {
Rs.close ();
}

finally {
Ps.close ();

finally {
Connection.close ();
}
catch (Exception ex) {
System.out.println ("Error:" + ex.getmessage ());
}
return returndate;
}

}
The output of this example is as follows:
Friday, October 5, 2001 10:42:34 PM EDT
Rows updated:1
Successfully retrieved last hit.
Friday, October 5, 2001 12:00:00 AM EDT
While this example does not provide a good performance method for saving and extracting date data, it does demonstrate how to convert Java Date data into SQL Date data for an update and DELETE statement. The process of setting an Oracle Date data field from a Java.util.Date object is handled by the following statement:
Ps.setdate (1, date);
It is a method of our predefined statement interface Java.sql.PreparedStatement.setDate.
This line of code appears in our Setlasthit method. It converts the long-integer date value of Java in microseconds to the SQL date format of Oracle. This conversion can be done when we can get date data from the database using Java.sql.PreparedStatement.getDate in the Getlasthit method.
You should also notice that only the date is set. Hours, minutes, seconds, and microseconds are not included in the conversion process from Java Date data to SQL Date data.
Conclusions
Once you have mastered these concepts, you should be able to create date objects based on system time or an input time. In addition, you should be able to format date data using standard and custom formatting processes, resolve date data for text to date objects, and display a date data in multiple languages and multiple time zones. Finally, you will be able to save and extract date values in an SQL database.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.