java.text.SimpleDateFormat set2DigitYearStart(Date startDate)

Description :

This java tutorial shows how to use the set2DigitYearStart(Date startDate) method of SimpleDateFormat class of java.text package. This method sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.

Method Syntax :

public void set2DigitYearStart(Date startDate)

Parameter Input :

 

DataType Parameter Description
Date startDate During parsing, two digit years will be placed in the range startDate to startDate + 100 years.

 

Method Returns :

This method returns void.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Discussion :

This method is helpful in fixing the current year we want to achieve. Lets take for an example a date input of 07/25/17 with format MM/dd/yy. What do you think is the result if we would be parsing this? Probably you would say it would be July 25, 2017. Yes, your answer would probably correct if you try to compile it now. But what if our intention is for the year to be 1917. That would be a problem which the set2DigitYearStart(Date startDate) intended to solve.

Java Code Example :

This java example source code demonstrates the use of set2DigitYearStart(Date startDate)  method of SimpledDateFormat class. Basically this code just parses the date and get the correct intepretation using the set2DigitYearStart  method.

package com.javatutorialhq.java.examples;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/*
 * This example source code demonstrates the use of  
 * set2DigitYearStart(Date startDate) method 
 * of SimpleDateFormat class
 */

public class Set2DigitYearStartExample {

	public static void main(String[] args) throws InterruptedException {

		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(sdf.parse("05/25/16"));		
			System.out.println("Time 1:"+cal.getTime());
			
			// we want 1916 instead of 2016
			sdf.set2DigitYearStart(sdf.parse("01/01/1900"));
			// set the value of calendar again 
			// to check if we now have the correct year
			cal.setTime(sdf.parse("05/25/16"));
			System.out.println("Time 2:"+cal.getTime());
			
		} catch (ParseException e) {
			e.printStackTrace();
		}	
	}
}

Sample Output :

Running the set2DigitYearStart(Date startDate) method example source code of Calendar class will give you the following output:

SimpleDateFormat set2DigitYearStart() method example

SimpleDateFormat set2DigitYearStart() method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :