How can I create a SHORT-style DateFormat with a four digit year that works for all locales?

Joe Sam Shirah

One method involves modifying the existing pattern from "yy" to "yyyy". The DateFormat factory methods generally return a SimpleDateFormat. Use SimpleDateFormat's toPattern() to retrieve the pattern String, insert the additional "yy" and then use applyPattern() with the modified pattern. Note that the documentation states "you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one." You can also use instanceof, which is the case in the following code sample.


import java.sql.*;
import java.text.*;
import java.util.*;

public class y4Format 
{
  java.sql.Date jsqlDate = new java.sql.Date( 
     System.currentTimeMillis() );

  DateFormat dfLocal = 
     SimpleDateFormat.getDateInstance( 
        DateFormat.SHORT );
  DateFormat dfGermany = 
     SimpleDateFormat.getDateInstance( 
        DateFormat.SHORT, Locale.GERMANY );

  int i, iLen;
  String sTemp;


  public y4Format()
  {
    System.out.println( "dfGermany before: " + 
       dfGermany.format( jsqlDate ) );
    if( dfGermany instanceof SimpleDateFormat )
    {
      doShortTo4( (SimpleDateFormat)dfGermany );
    }

    System.out.println( "dfGermany after: " + 
       dfGermany.format( jsqlDate ) );
    System.out.println();

    System.out.println( "dfLocal before: " + 
       dfLocal.format( jsqlDate ) );
    if( dfLocal instanceof SimpleDateFormat )
    {
      doShortTo4( (SimpleDateFormat)dfLocal );
    }

    System.out.println( "dfLocal after: " + 
       dfLocal.format( jsqlDate ) );

  }  // end constructor



  public void doShortTo4( SimpleDateFormat sdf )
  {
    System.out.println( 
      "before - Pattern: " + 
       sdf.toPattern() + ",   " +
      "LocalizedPattern: " + 
       sdf.toLocalizedPattern() );

    sTemp = sdf.toPattern();
    iLen = sTemp.length();
    i = sTemp.lastIndexOf( 'y' ) + 1;
    sTemp =  sTemp.substring(  0, i ) + 
            "yy" + 
            ( i < iLen 
              ?  sTemp.substring( i, iLen )
              :  "" );
    sdf.applyPattern( sTemp );

    System.out.println( 
      "after  - Pattern: " + 
       sdf.toPattern() + ", " +
      "LocalizedPattern: " + 
       sdf.toLocalizedPattern() );

  } // end do4


  public static void main(String[] args)
  {
    new y4Format();
  }

}  // end class y4Format
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact