Java – Format Date Object to String

In this topic we going to explain about, how to format a date object into a string in java.
Most of the time we use string for printing date in JSP. But java, don’t String as a date. Java only know date as data object. This results we need to format with java.text package SimpleDateFormat class. This class have method of format to date object.

We have to pass format method a java.util.Date object. This simple date format return date in our required format. This return as us a string data type. This string can easily use in JSP program.

First we need to take Date object and create new variable of date. This date can now pass in format method of simple date format and it format and return result.

Letter Date or Time Presentation Result Examples
G Era designator Text AD
yyyy, yy Year Year 2009; 09
MMMM, MMM, MM Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
dd Day in month Number 10
F Day of week in month Number 2
EEEE, E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
HH Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
hh Hour in am/pm (1-12) Number 12
mm Minute in hour Number 30
ss Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800

The example will explain more about formatting date into a string of required format.

<%@ page language="java" import="java.text.SimpleDateFormat" errorPage="" %>
<%
    String dateFormat="02/28/2009";
    ///java.util.Date currentDate=new java.util.Date(); /// for current date
    String dformat=new SimpleDateFormat("yyyy-MMM-dd EEEE").format(new java.util.Date(dateFormat));
    ///String df=new SimpleDateFormat("yyyy-MMM-dd EEEE").format(currentDate);
%>
<html>
<head>
<title>Format Date Object to String</title>
</head>

<body>
Date : <%=dformat%>
</body>
</html>

Second example of date in java

import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat {
    public static void main(String[] args) {
        String dateFormat="02/28/2009";
        ///java.util.Date currentDate=new java.util.Date(); /// for current date
        String df=new SimpleDateFormat("yyyy-MMM-dd EEEE").format(new java.util.Date(dateFormat));
        ///String df=new SimpleDateFormat("yyyy-MMM-dd EEEE").format(currentDate);
        System.out.println("Date :"+df);
    }
}
Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post