• Chennai, Bangalore & Online: 93450 45466Coimbatore: 95978 88270Madurai: 97900 94102

  • 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

      93450 45466

    Bangalore

     93450 45466

    Coimbatore

     95978 88270

    For Hiring

     93840 47472
     hr@fita.in

    Corporate Training

     90036 23340


    FITA Academy Branches

    Chennai
    Bangalore
    Coimbatore
    Other Locations
    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 and Opposite to Nilgris Supermarket

        :   93450 45466

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

        :   93450 45466

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

        :   93450 45466

    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

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

        :   97900 94102

  • Trending Courses

    JAVA Training In Chennai Dot Net Training In Chennai Software Testing Training In Chennai Cloud Computing Training In Chennai AngularJS Training in Chennai Big Data Hadoop Training In Chennai Android Training In Chennai iOS Training In Chennai Web Designing Course In Chennai PHP Training In Chennai Digital Marketing Course In Chennai SEO Training In Chennai

    Oracle Training In Chennai Selenium Training In Chennai Data Science Course In Chennai RPA Training In Chennai DevOps Training In Chennai C / C++ Training In Chennai UNIX Training In Chennai Placement Training In Chennai German Classes In Chennai Python Training in Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai Core Java Training in Chennai Javascript Training in ChennaiHibernate Training in ChennaiHTML5 Training in ChennaiPhotoshop Classes in ChennaiMobile Testing Training in ChennaiQTP Training in ChennaiLoadRunner Training in ChennaiDrupal Training in ChennaiManual Testing Training in ChennaiSpring Training in ChennaiStruts Training in ChennaiWordPress Training in ChennaiSAS Training in ChennaiClinical SAS Training in ChennaiBlue Prism Training in ChennaiMachine Learning course in ChennaiMicrosoft Azure Training in ChennaiUiPath Training in ChennaiMicrosoft Dynamics CRM Training in ChennaiUI UX Design course in ChennaiSalesforce Training in ChennaiVMware Training in ChennaiR Training in ChennaiAutomation Anywhere Training in ChennaiTally course in ChennaiReactJS Training in ChennaiCCNA course in ChennaiEthical Hacking course in ChennaiGST Training in ChennaiIELTS Coaching in ChennaiSpoken English Classes in ChennaiSpanish Classes in ChennaiJapanese Classes in ChennaiTOEFL Coaching in ChennaiFrench Classes in ChennaiInformatica Training in ChennaiInformatica MDM Training in ChennaiBig Data Analytics courses in ChennaiHadoop Admin Training in ChennaiBlockchain Training in ChennaiIonic Training in ChennaiIoT Training in ChennaiXamarin Training In ChennaiNode JS Training In ChennaiContent Writing Course in ChennaiAdvanced Excel Training In ChennaiCorporate Training in ChennaiEmbedded Training In ChennaiLinux Training In ChennaiOracle DBA Training In ChennaiPEGA Training In ChennaiPrimavera Training In ChennaiTableau Training In ChennaiSpark Training In ChennaiGraphic Design Courses in ChennaiAppium Training In ChennaiSoft Skills Training In ChennaiJMeter Training In ChennaiPower BI Training In ChennaiSocial Media Marketing Courses In ChennaiTalend Training in ChennaiHR Courses in ChennaiGoogle Cloud Training in ChennaiSQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai

  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur 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!