Home Java Java-conversion Java Date Conversion
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java Date Conversion

Advertisement
In java date conversion, two packages are used .They are java.util.* and java.text.*. The java.util.* package provides three subclasses that are named as java.util.Date, java.util.Time and java.util.Timestamp class.

Java Date Conversion

In java date conversion, two packages are used .They are  java.util.* and java.text.*. The java.util.* package provides three subclasses that are named as java.util.Date, java.util.Time and java.util.Timestamp class.

The  java.util.Date class represents a specific instant in time. The time is with millisecond precision. In JDK 1.1, the  java.util.Date class has two additional functions. It allows the interpretation of date in year, month, day, hour, minute, and second values. It also allows the formatting and parsing of date strings. The Calendar class of JDK 1.1 is  used to convert between dates and time fields and the DateFormat class is  used to format and parse date strings. The  Date class supports the universal time (UTC). That means 1 day = 24 60 60 = 86400 seconds in all cases. 
All methods of  Date either accept or return values in year, month, day, hour, minute, and second. 
The following representations are used: 

1.  y is used to represent an year  which is an integer value. The value will be y-19000. 
2.  m  is used to represent a month which has values  form 0 to 11. In which 0 is used for January, 1 is used for February and so on, thus 11 is used for December. 
3.  A date (day of month) is represented by an integer from 1 to 31 in the usual manner. 
4.  An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12
5.  A minute is represented by an integer from 0 to 59 in the usual manner. 
6.  A second is represented by an integer from 0 to 61, the values 60 and 61 occur only for leap seconds and even then only Java provides implementation that actually track leap seconds correctly. 

The Constructor of  Date:
Date(): This constructor is used to allocate a Date object and initializes it. The object used to represent the time and date is  measured in nearest milliseconds. The following constructors has been deprecated and are  replaced by Calendar.set(year + 1900, month, date) / GregorianCalendar(year + 1900, month, date), Calendar.set(year + 1900, month, date, hrs, min) / GregorianCalendar(year + 1900, month, date, hrs, min) and Calendar.set(year + 1900, month, date, hrs, min, sec) / GregorianCalendar(year + 1900, month, date, hrs, min, sec) respectively. 

Date(int year, int month, int date)

Date(int year, int month, int date, int hrs, int min) 
Date(int year, int month, int date, int hrs, int min, int sec)

Date(long date): This is used to allocate a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. 

Date(String s): This is deprecated. It is  replaced by DateFormat.parse(String s).

The java.text.* pacakge  is used for formatting and parsing of dates. It allows formatting of text from date , parsing from date to date  and normalization. The java.text.DatefFormat class is the super class of  java.text.SimpleDateFormat class. The java.text.SimpleDateFormat is a concrete class for formatting and parsing of dates. The java.text.SimpleDateFormat class allows us to start the user defined patterns for date-time formatting. We can encourage to anyone to create a date-time formatter with either getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat. The methods  within the class returns a date/time.formatter with a default format pattern.

To specify the time format using a time pattern string all ASCII letters are reserved as pattern letters, which are defined as the following: 

Symbol Meaning  Presentation  Example
G   era designator (Text)  AD
y year  (Number)  1996
month in year  (Text & Number)  July & 07
day in month  (Number)  10
hour in am/pm (1~12)  (Number)  12
hour in day 0~23) ( (Number)  1
minute in hour  (Number)  30
second in minute  (Number)  55
S  millisecond  (Number)  978
day in week  (Text)  Tuesday
day in year  (Number)  189
day of week in month  (Number)  2 (2nd Wed in July)
week in year  (Number)  27
week in month  (Number)  2
am/pm marker  (Text)  PM

hour in day (1~24)  (Number)  24
hour in am/pm (0~11)  (Number)  0
time zone  (Text)  Pacific Standard Time

Java Converts String into Date

In this example we are going to convert string into date. We are creating DateFormat by using SimpleDateFormat then parse the string with the date format. We are creating an object of Date to store the parsed formatted string. 
The method used:
parse(String text):
This method is used to parse date/time string into date. The return type of this method is Date. This method throws ParseExceptionParse Exception if the given string cannot be parsed as a date.

 The code of the program is given below:

import java.util.*;
import java.text.*;
public class StringToDate {
 public static void main(String[] args) {
 try {  String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date);  
 System.out.println("Today is " +date );
  catch (ParseException e)
  {System.out.println("Exception :"+e);  }  
 
 }
}  

The output of the program is given below:

C:\date>javac StringToDate.java

C:\date>java StringToDate
Today is Mon Jun 11 00:00:00 GMT+05:30 2007

Download this example.

Java Converts Date into String

In this example we are converting  date into string. In  this example we are using format method to convert date into string.
The method used:
format(Date date): This method is defined as final in DateFormat class. This is used to format a Date into a date/time string. The parameter passed is as date/time and the return type of this method is string.

 The code of the program is given below:

import java.util.*;
import java.text.*;
public class DateToString {
 public static void main(String[] args) {
 try {
 DateFormat formatter ; 
 Date date ;  
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse("11-June-07");  
  String s = formatter.format(date);
  System.out.println("Today is " + s);
  catch (ParseException e)
  {System.out.println("Exception :"+e);  }  
 
 }
}  

The output of the program is given below:

C:\date>javac DateToString.java
C:\date>java DateToString
Today is 11-Jun-07

Download this example.

Java Converts Date into Long

In this example we are converting  date into long. In  this example we are using getTime() method to get time/date as long return type.
The method used:
getTime(): This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. The return type of this method is long.

 The code of the program is given below:

import java.util.*;
import java.text.*;
public class DateToLong {
 public static void main(String[] args) {
 try {  String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date); 
 long longDate=date.getTime();
 System.out.println("Today is " +longDate );
  catch (ParseException e)
  {System.out.println("Exception :"+e);  }  
 
 }
}  


  

The output of the program is given below:

C:\date>javac DateToLong.java
C:\date>java DateToLong
Today is 1181500200000

Download this example.

Java Converts Date into Milliseconds

In this example we are converting  date into milliseconds. In  this example we are using getTime() method to get time/date as long return type.
The method used:
getTime(): The method getTime() uses the time in milliseconds. 

 The code of the program is given below:

import java.util.*;
import java.text.*;
import java.sql.Timestamp;
public class DateToMilliseconds {
 public static void main(String[] args) {
 Date date=new Date() ;  
 System.out.println("Today is " +date.getTime());
  
}    

The output of the program is given below:

C:\date>javac DateToMilliseconds.java
C:\date>java DateToMilliseconds
Today is 1181644914093

Download this example.

Java Converts Long into Date

In this example we are converting  Long value into Date. In  this example we are using getDateInstance() method as time formatter with the given formatting style for the default locale. In this example we are using the style as long.
The method used:
getTimeInstance(int style): This method is used to get the time formatter with the given formatting style for the default locale. Here style gives the formatting style.
Some other styles are:
FULL
LONG
MEDIUM
SHORT
DEFAULT

Its value is MEDIUM.

The code of the program is given below:

import java.util.*;
import java.text.*;
public class LongToDate {
 public static void main(String[] args)throws Exception {
 Date date = new Date();
  DateFormat dataformat =  DateFormat.
getDateInstance(DateFormat.LONG);
 
  String s4 = dataformat.format(date);
 System.out.println(dataformat.format(date));  
  } }  

The output of the program is given below:

C:\date>javac LongToDate.java
C:\date>java LongToDate
June 12, 2007

Download this example.

Java Converts Milliseconds into Date

In this example we are converting  Milliseconds into Date. Here we are passing the value into Date class as an argument. Which will be considered by Date class in millisecond. We are using formatter to format the date.

 The code of the program is given below:

import java.util.*;
import java.text.*;
public class MillisecondToDate {
 public static void main(String[] args)throws Exception {
 long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
 
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));  
}    

The output of the program is given below:

C:\date>javac MillisecondToDate.java
C:\date>java MillisecondToDate
Jan 14,1970 04:23

Download this example. 

Java Converts String into Calendar

In this example we are converting  string value into Calendar. In this example we are creating an object of Calendar in which we are storing an  instance of Calendar. We are using setTime(Date date) to set the formatted date into Calendar. We are passing a string just to parse it. 

 The code of the program is given below:

import java.util.*;
import java.text.*;
public class StringToCalender {
 public static void main(String[] args) {
 try {  String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date); 
 Calendar cal=Calendar.getInstance();
 cal.setTime(date);
 System.out.println("Today is " +date );
  catch (ParseException e)
  {System.out.println("Exception :"+e);  } 
 
 }
  

The output of the program is given below:

C:\date>javac StringToCalender.java
C:\date>java StringToCalender
Today is Mon Jun 11 00:00:00 GMT+05:30 2007M

Download this example.

Java Converts Date into Timestamp

In this example we are converting  date into a timestamp format. The java.sql.Timestamp class is a thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP value in nano seconds.It also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values. In this example we are just passing the time into an object of  java.sql.Timestamp class as an argument. 

 The code of the program is given below:

import java.util.*;
import java.text.*;
import java.sql.Timestamp;
public class DateToTimestamp {
 public static void main(String[] args) {
 try {  String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date); 
  java.sql.Timestamp timeStampDate = new 
Timestamp(date.getTime());
 System.out.println("Today is " +timeStampDate);
  catch (ParseException e)
  {System.out.println("Exception :"+e);  }  
 
 }
}   

The output of the program is given below:

C:\date>javac DateToMilliseconds.java
C:\date>java DateToMilliseconds
Today is 1181648109265

Download this example.

Java Converts Date into GMT

In this example we are converting  date into GMT. The java.util.SimpleTimeZone class is a concrete subclass of TimeZone class  that represents a time zone for use with a Gregorian calendar. This class holds an offset from GMT, called raw offset, It starts and ends rules for a daylight saving time schedule. 
In this example we are creating an instance of Calendar and storing it into an object. We are selecting the time zone GMT.

The code of the program is given below:

import java.util.*;
import java.text.*;
public class DateToGMT {
 public static void main(String[] args)throws Exception {
  
  java.text.SimpleDateFormat format0 = 
new 
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  java.util.Calendar cal0 = Calendar.
getInstance(
new SimpleTimeZone(0"GMT"));
  format0.setCalendar(cal0);
  java.util.Date date = format0.
parse(
"2003-01-25 00:15:30");
  System.out.println(date);  
  
}    

The output of the program is given below:

C:\date>javac DateToGMT.java
C:\date>java DateToGMT
Sat Jan 25 05:45:30 GMT+05:30 2003

Download this example.

Java Converts Milliseconds into Time

In this example we are converting  milliseconds to time. 
We can  use a format to convert  milliseconds into time. The format mm:hh is used to display the time.

The code of the program is given below:

import java.util.*;
import java.text.*;
public class MillisecondToTime {
 public static void main(String[] args)throws Exception {
 long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("mm:hh");
 
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

  
  

The output of the program is given below:

C:\date>javac MillisecondToTime.java
C:\date>java MillisecondToTime
23:04

Download this example.

Java Converts Milliseconds into Minutes

In this example we are converting milliseconds into minutes. 
We can also directly convert milliseconds into minutes by dividing 1000 and then multiply by 60.

The code of the program is given below:

import java.util.*;
import java.text.*;
public class MillisecondToMinute {
 public static void main(String[] args)throws Exception {
 long yourmilliseconds = 1119193190;
 long minute=yourmilliseconds/1000*60;

System.out.println(minute);

  } }   

The output of the program is given below:

C:\date>javac MillisecondToMinute.java
C:\date>java MillisecondToMinute
67151580

Download this example.

Java Converts Date into Calendar

In this example we are converting  date into Calendar. Here we are using format method to convert date into string. We are using java.util. Calendar class in this example. The GregorianCalendar class is subclass of the Calendar class. Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. A Date object represents a specific instant of time with millisecond precision The subclasses of Calendar class  interpret a Date according to the rules of a specific calendar system. Calendar class  provides a class method getInstance to get a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose time fields have been initialized with the current date and time. e.g
Calendar rightNow = Calendar.getInstance();

A Calendar object can produce all the time field values needed to implement the date-time format for a particular language and calendar style.

The method used:
getInstance():
This method is define as public, static and final in Calendar class The return type of this method is DateFormat. This method is used  to get a default date/time formatter that uses the SHORT style for both date and time.

setTime(long time):
This method is used to set the date object to represent a time in milliseconds after January 1, 1970 00:00:00 GMT. 

In this example we are going to get date instance from system then parse and convert it into a Calendar set formatted date in a Calendar object.

The code of the program is given below:

import java.util.*;
import java.text.*;
public class DateToCalender {
public static void main(String[] args) {
 try {  String str_date="11-June-07";
  DateFormat formatter ; 
  Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date); 
 Calendar cal=Calendar.getInstance();
 cal.setTime(date);
 System.out.println("Today is " +cal );
  }
  catch (ParseException e)
  {System.out.println("Exception :"+e);  }  
 
 }
}  

The output of the program is given below:

C:\date>javac DateToCalender.java
C:\date>java DateToCalender
Today is java.util.GregorianCalendar[time=1181500200000,areFieldsSet=true,areAll
FieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+05:30",offse
t=19800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayO
fWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2007,MONTH=5,WEEK_OF_YEAR=24,WEEK_OF
_MONTH=3,DAY_OF_MONTH=11,DAY_OF_YEAR=162,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM
_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,
DST_OFFSET=0]

Download this example.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 14, 2008

Ask Questions?    Discuss: Java Date Conversion  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com