Recently I had a difficulty in setting the Date Labels using the Date Functions in Java Swings application that I was working on. The reason being that there are two variants of the Date Functions:-
- java.sql.Date
- java.util.Date.
If we use java.util.Date then java.sql.Date function was not accessible and java.sql.Date was required for setting the date using Prepared Statements.
I managed to rectify it by type-casting the two functions. Below are a set of ways in which the Date functions
can be used:
JAVA.UTIL.DATE
- Setting the Date in a JLabel in string format
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
JLabel date= new JLabel("DATE:");
final JLabel dateTime = new JLabel();
dateTime.setText(Demo.timenow()); // Demo is the name of the jframe
public static String timeNow() {
Calendar cal = Calendar.getInstance();
String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
JAVA.SQL.DATE
- Printing the date in string format
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Dates {
private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");
public static void main(String[] args){
Date oneDate = new Date(new java.util.Date().getTime());
System.out.println(df.format(oneDate));
}
- Returing the date in DATE format
import java.sql.Date;
private static java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
- Setting date value as timestamp using prepared staments
import java.sql.Date;
java.util.Date today2 = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today2.getTime());
prepst.setTimestamp(2, timestamp);
- Setting date value through Hibernate
import java.sql.Date;
String date2= dateTime.getText(); // set date to a string which is fetched from a JLabel dateTime
java.util.Date date = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss").parse(date2); /*changing
date format*/
bill.setDate(date);
The are more tutorials and tips coming up in java. These are some basic tips and techniques that are used while coding for swings applications. Some common bugs that would be encountered and rectified easily.
No comments:
Post a Comment