For Enquiry: 93450 45466

Date class In Java: Formatting dates in java


In this blog, we will learn about the date class of the java, customizing the date formats along with the example programs, with this table of contentโ€ฆ
Date Class in java
Constructors of the date class
Methods of the date class
Formatting dates with the DateFormat class
Converting date to a string in java
Formatting dates with SimpleDateFormat class
Converting a string to date in java
Formatting dates with DateTimeFormatter class
Converting date to custom format with off pattern() method
Let us start with understanding the Date class and Date objects in java

Date Class in java

Date in java can be represented as an object of the class, Date, which is present at the java.util package implementing the comparable interface, serializable interface, and cloneable interface.

There are methods and constructors available to customize the data and time in java. Constructors of the date class
Date(): Creates an instance of the Date Class for representing the current date and time.
Date(long milliseconds): Creates an instance of the Date Class for the given milliseconds.
Let us now see these constructors in action, by implementing them in an example program.

// Java program for demonstrating the constructors of the Date Class
import java.util.*;
 
public class Main {
public static void main(String[] args) {
Date dt1 = new Date();
System.out.println("Today's date is " + dt1);
Date dt2 = new Date(2323223233L);
System.out.println("GIven data is represented as " + dt2);
}
}
Output for the above program will be

Today's date is Fri Oct 09 13:27:13 UTC 2020
GIven data is represented as Tue Jan 27 21:20:23 UTC 1970
Methods of the date class
boolean after(Date date): Checks for the given date is earlier than the current data.
boolean before(Date date): Checks for the given date if it comes after the current data.
int compareTo(Date date): Compares the given date with the current date.
Returns 0, if the passed Date is equal to theย  Date object.
A positive value, if the passed Date comes before theย  Date object.
A negative value, if the passed Date comes after theย  Date object.
void setTime(long time): Changes the current date and time to a given time.
Let us now see these methods in action, by implementing them in an example program.

// Example program for demonstrating methods of Date class
import java.util.*;
 
public class Main {
public static void main(String[] args) {
// Creating dates
Date dt1 = new Date(2003, 12, 22);
Date dt2 = new Date();ย  ย  ย  ย  ย  ย  // Today's date
Date dt3 = new Date(2010, 12, 7);
 
boolean afr = dt1.after(dt2);
System.out.println("Date 2003/12/22 comes after " + "today's date: " + afr);
 
boolean bfr = dt2.before(dt3);
System.out.println("Today's date comes before " + "date 2010/12/7: " + bfr);
 
int com = dt3.compareTo(dt2);
System.out.println(com);
 
System.out.println(" Date Before setting: " + dt2);
dt2.setTime(204587433443L);
System.out.println("Date After setting with setTime: " + dt2);
}
}
Output for the above program will be

Date 2003/12/22 comes after today's date: true
Today's date comes before date 2010/12/7: true
1
Date Before setting: Fri Oct 09 13:38:52 UTC 2020
Date After setting with setTime: Fri Jun 25 21:50:33 UTC 1976

Now customizing these date formats will require us to use the DateFormat class, the SimpleDateFormat class, or the offpattern() method of the DateTimeFormatter class. So let us see each of them one by one in the following sequence

Formatting dates with the DateFormat class.
Formatting dates with SimpleDateFormat class.
Formatting dates with DateTimeFormatter class.
Let us format dates with each of these classes, starting with the DateFormat class.

Formatting dates with the DateFormat class in java

The DateFormat class is an asynchronous class,ย  present at java.text.DateFormat.This class provides various methods to format dates and also to parse the dates to a String.

Let us see an example for implementing the DateFormat class. Converting Date to a String in java Let use the DateFormat class, for converting a given date to a string.

// Example Program to format date with the DateFormat class
import java.util.*;
import java.text.*;
import java.util.Calendar;
 
public class Main {
public static void main(String[] args) {
 
DateFormat Date = DateFormat.getDateInstance();// date formatter
 
Calendar cal = Calendar.getInstance(); // calender object
 
System.out.println("The actual Date: " + cal.getTime());
 
// Using format() method of DateFormat for converting date to string
String ForD = Date.format(cal.getTime());
System.out.println("Formatted Date: " + ForD);
}
}
Output for the above program

The actual Date: Fri Oct 09 13:55:28 UTC 2020
Formatted Date: Oct 9, 2020
After learning to format dates with the DateFormat class, let us now learn to format dates with the SimpleDateFormat class in java.

Check out this Complete Java Online Training by FITA. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real time applications using Servlets, Hibernate Framework, and Spring with Aspect-Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, by expert software developers with over 10 years of experience in the field to make you an industry required certified java developer.

Formatting dates with the SimpleDateFormat class in java

This is the child class of DateFormat class which takes a String argument that should specify the pattern or formatting pattern of the date. The years should be represented by โ€˜yyyyโ€™,ย  month by โ€˜MMโ€™ and the date by โ€˜ddโ€™. Let us implement the SimpleDateFormat class with an example program.

Converting String to a Date in java


// Example Program to format date with the DateFormat class
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main {
public static void main(String[] args) {
String pattern = "dd/MM/yyyy";
SimpleDateFormat DateFor = new SimpleDateFormat(pattern);
try {
Date date = DateFor.parse("20/05/2016");
System.out.println("Date : " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output for the above program

Date : Fri May 20 00:00:00 UTC 2016
After learning to format dates with the SimpleDateFormat class, let us now learn to format dates with the DateTimeFormatter class in java.

Formatting dates with DateTimeFormatter class in java

The ofpattern() method of the DateTimeFormatter class can be used on LocalDateTime instance, to format or parse the date or time object of the class.

// Example Program to format date with the DateTimeFormatter class
import java.util.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
public class Main {
public static void main(String[] args) {
LocalDateTime dtobj = LocalDateTime.now();
System.out.println("Date before formatting: " + dtobj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy, HH-mm-ss");
 
String fdt = dtobj.format(myFormatObj);
System.out.println("Date after formatting: " + fdt);
}
}
Output for the above program

Date before formatting: 2020-10-09T14:21:51.602193
Date after formatting: 09-10-2020, 14-21-51

This was all about strings, arrays, and string arrays in java along with practice programs. To get in-depth knowledge of the core Java and advanced java, J2EEย  SOA training along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework, and Struts through JDBC you can enroll in Certified Java Training in Chennai or Certified Java Training in Bangalore by FITA or a virtual class for this course, at an affordable price, bundled with real-time projects, certification, support, and career guidance assistance and an active placement cell, to make you an industry required certified java developer.

FITAโ€™s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.






Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai, Bangalore & Online

  93450 45466

Coimbatore

 95978 88270

Pondicherry

93635 21112

Madurai

97900 94102

Tirupur

99401 22502

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


FITA Academy Branches

Chennai

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office
& Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy - Pallikaranai
335A, 13th Main Rd,
Ram Nagar South Extn,
Pallikaranai, Chennai,
Tamil Nadu 600100

    :   93450 45466

Bangalore

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

Coimbatore

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

Other Locations

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

FITA Academy - Tiruppur
61D, Poongodi Towers 2nd floor,
Periyar Colony Bus Stop,
Tirupur - 641 652

    :   9940122502

Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!