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.





  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai

  • 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!