How to format year using SimpleDateFormat in Java?

JavaServer Side ProgrammingProgramming

The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string. To parse a date string −

  • Instantiate this class by passing desired format string.
  • Parse the date string using the parse() method.

Example

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
   public static void main(String args[]) throws ParseException {  
      SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm:ss");      
      Date time1 = formatter1.parse("07:25:30");
      System.out.println("Date value: "+time1);
      SimpleDateFormat formatter3 = new SimpleDateFormat("hh 'o''clock' a");      
      Date time3 = formatter3.parse("09 o'clock AM");
      System.out.println("Date value: "+time3);
   }
}

Output

Date value: Thu Jan 01 07:25:30 IST 1970
Date value: Thu Jan 01 09:00:00 IST 1970

Formatting the Year

Following are the letters to format the year using the SimpleDateFormat class.

Letter

Component

Example

y
Year
2005, 96
Y
Week year
2005, 96

Example

Following example demonstrates how to format the year using the SimpleDateFormat class −

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example {
   public static void main(String args[]) throws ParseException {  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/dd/MM");      
      Date date = formatter.parse("2007/25/06");
      System.out.println("Date value: "+date);    
      formatter = new SimpleDateFormat("y:G");      
      date = formatter.parse("1920:BC");
      System.out.println("Date value: "+date);      
      formatter = new SimpleDateFormat("D-M-Y");      
      date = formatter.parse("25-05-1989");
      System.out.println("Date value: "+date);
   }
}

Output

Date value: Mon Jun 25 00:00:00 IST 2007
Date value: Sun Jan 01 00:00:00 IST 1920
Date value: Sun Jan 01 00:00:00 IST 1989
raja
Published on 06-Feb-2021 08:22:41
Advertisements