Java/Data Type/Date Format

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Add AM PM to time using SimpleDateFormat

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDateFormat = "HH:mm:ss a";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println(sdf.format(date));
 }

} //10:20:12 AM



 </source>
   
  
 
  



An alternate way to get week days symbols

   <source lang="java">
  

import java.text.DateFormatSymbols; import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   String dayNames[] = new DateFormatSymbols().getWeekdays();
   Calendar date2 = Calendar.getInstance();
   System.out.println("Today is a " + dayNames[date2.get(Calendar.DAY_OF_WEEK)]);
 }

}


 </source>
   
  
 
  



Change date formatting symbols

   <source lang="java">
  

import java.text.SimpleDateFormat; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.util.Date; public class Main {

 public static void main(String[] args) {
   String[] newMonths = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
       "NOV", "DEC" };
   String[] newShortMonths = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep",
       "oct", "nov", "dec" };
   String[] newWeekdays = { "", "Monday", "Tuesday", "Webnesday", "Thursday", "Friday",
       "Saturaday", "Sunday" };
   String[] shortWeekdays = { "", "monday", "tuesday", "webnesday", "thursday", "friday",
       "saturaday", "sunday" };
   DateFormatSymbols symbols = new DateFormatSymbols();
   symbols.setMonths(newMonths);
   symbols.setShortMonths(newShortMonths);
   symbols.setWeekdays(newWeekdays);
   symbols.setShortWeekdays(shortWeekdays);
   DateFormat format = new SimpleDateFormat("dd MMMM yyyy", symbols);
   System.out.println(format.format(new Date()));
   format = new SimpleDateFormat("dd MMM yyyy", symbols);
   System.out.println(format.format(new Date()));
   format = new SimpleDateFormat("EEEE, dd MMM yyyy", symbols);
   System.out.println(format.format(new Date()));
   format = new SimpleDateFormat("E, dd MMM yyyy", symbols);
   System.out.println(format.format(new Date()));
 }

}


 </source>
   
  
 
  



Date Era change

   <source lang="java">
    

import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; public class ChangeEra {

 public static void main(String s[]) {
   SimpleDateFormat sdf = new SimpleDateFormat();
   DateFormatSymbols dfs = sdf.getDateFormatSymbols();
   String era[] = { "BCE", "CE" };
   dfs.setEras(era);
   sdf.setDateFormatSymbols(dfs);
   sdf.applyPattern("MMMM d yyyy G");
   System.out.println(sdf.format(new Date()));
 }

}



 </source>
   
  
 
  



Date Format

   <source lang="java">
    

import java.text.SimpleDateFormat; import java.util.Date; class DateFormatApp {

 public static void main(String args[]) {
   String pattern = ""The year is "";
   pattern += "yyyy GG";
   pattern += "".\nThe month is "";
   pattern += "MMMMMMMMM";
   pattern += "".\nIt is "";
   pattern += "hh";
   pattern += "" o""clock "";
   pattern += "a, zzzz";
   pattern += ""."";
   SimpleDateFormat format = new SimpleDateFormat(pattern);
   String formattedDate = format.format(new Date());
   System.out.println(formattedDate);
 }

}



 </source>
   
  
 
  



Date Format Cache

   <source lang="java">
 

// // Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //

import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /* ------------------------------------------------------------ */ /** Date Format Cache.

* Computes String representations of Dates and caches
* the results so that subsequent requests within the same minute
* will be fast.
*
* Only format strings that contain either "ss" or "ss.SSS" are
* handled.
*
* The timezone of the date may be included as an ID with the "zzz"
* format string or as an offset with the "ZZZ" format string.
*
* If consecutive calls are frequently very different, then this
* may be a little slower than a normal DateFormat.
*
* @author Kent Johnson <KJohnson@transparent.ru>
* @author Greg Wilkins (gregw)
*/

public class DateCache {

   private static long __hitWindow=60*60;
   private static long __MaxMisses=10;
   
   private String _formatString;
   private String _tzFormatString;
   private SimpleDateFormat _tzFormat;
   
   private String _minFormatString;
   private SimpleDateFormat _minFormat;
   private String _secFormatString;
   private String _secFormatString0;
   private String _secFormatString1;
   private boolean _millis=false;
   private long _misses = 0;
   private long _lastMinutes = -1;
   private long _lastSeconds = -1;
   private String _lastResult = null;
   private Locale _locale  = null;
   private DateFormatSymbols _dfs  = null;
   /* ------------------------------------------------------------ */
   /** Constructor.
    * Make a DateCache that will use a default format. The default format
    * generates the same results as Date.toString().
    */
   public DateCache()
   {
       this("EEE MMM dd HH:mm:ss zzz yyyy");
       getFormat().setTimeZone(TimeZone.getDefault());
   }
   
   /* ------------------------------------------------------------ */
   /** Constructor.
    * Make a DateCache that will use the given format
    */
   public DateCache(String format)
   {
       _formatString=format;
       setTimeZone(TimeZone.getDefault());
       
   }
   
   /* ------------------------------------------------------------ */
   public DateCache(String format,Locale l)
   {
       _formatString=format;
       _locale = l;
       setTimeZone(TimeZone.getDefault());       
   }
   
   /* ------------------------------------------------------------ */
   public DateCache(String format,DateFormatSymbols s)
   {
       _formatString=format;
       _dfs = s;
       setTimeZone(TimeZone.getDefault());
   }
   /* ------------------------------------------------------------ */
   /** Set the timezone.
    * @param tz TimeZone
    */
   public void setTimeZone(TimeZone tz)
   {
       setTzFormatString(tz);        
       if( _locale != null ) 
       {
           _tzFormat=new SimpleDateFormat(_tzFormatString,_locale);
           _minFormat=new SimpleDateFormat(_minFormatString,_locale);
       }
       else if( _dfs != null ) 
       {
           _tzFormat=new SimpleDateFormat(_tzFormatString,_dfs);
           _minFormat=new SimpleDateFormat(_minFormatString,_dfs);
       }
       else 
       {
           _tzFormat=new SimpleDateFormat(_tzFormatString);
           _minFormat=new SimpleDateFormat(_minFormatString);
       }
       _tzFormat.setTimeZone(tz);
       _minFormat.setTimeZone(tz);
       _lastSeconds=-1;
       _lastMinutes=-1;        
   }
   /* ------------------------------------------------------------ */
   public TimeZone getTimeZone()
   {
       return _tzFormat.getTimeZone();
   }
   
   /* ------------------------------------------------------------ */
   /** Set the timezone.
    * @param timeZoneId TimeZoneId the ID of the zone as used by
    * TimeZone.getTimeZone(id)
    */
   public void setTimeZoneID(String timeZoneId)
   {
       setTimeZone(TimeZone.getTimeZone(timeZoneId));
   }
   
   /* ------------------------------------------------------------ */
   private void setTzFormatString(final  TimeZone tz )
   {
       int zIndex = _formatString.indexOf( "ZZZ" );
       if( zIndex >= 0 )
       {
           String ss1 = _formatString.substring( 0, zIndex );
           String ss2 = _formatString.substring( zIndex+3 );
           int tzOffset = tz.getRawOffset();
           
           StringBuffer sb = new StringBuffer(_formatString.length()+10);
           sb.append(ss1);
           sb.append(""");
           if( tzOffset >= 0 )
               sb.append( "+" );
           else
           {
               tzOffset = -tzOffset;
               sb.append( "-" );
           }
           
           int raw = tzOffset / (1000*60);   // Convert to seconds
           int hr = raw / 60;
           int min = raw % 60;
           
           if( hr < 10 )
               sb.append( "0" );
           sb.append( hr );
           if( min < 10 )
               sb.append( "0" );
           sb.append( min );
           sb.append( "\"" );
           
           sb.append(ss2);
           _tzFormatString=sb.toString();            
       }
       else
           _tzFormatString=_formatString;
       setMinFormatString();
   }
   
   /* ------------------------------------------------------------ */
   private void setMinFormatString()
   {
       int i = _tzFormatString.indexOf("ss.SSS");
       int l = 6;
       if (i>=0)
           _millis=true;
       else
       {
           i = _tzFormatString.indexOf("ss");
           l=2;
       }
       
       // Build a formatter that formats a second format string
       // Have to replace @ with " later due to bug in SimpleDateFormat
       String ss1=_tzFormatString.substring(0,i);
       String ss2=_tzFormatString.substring(i+l);
       _minFormatString =ss1+(_millis?""ss.SSS"":""ss"")+ss2;
   }
   /* ------------------------------------------------------------ */
   /** Format a date according to our stored formatter.
    * @param inDate 
    * @return Formatted date
    */
   public synchronized String format(Date inDate)
   {
       return format(inDate.getTime());
   }
   
   /* ------------------------------------------------------------ */
   /** Format a date according to our stored formatter.
    * @param inDate 
    * @return Formatted date
    */
   public synchronized String format(long inDate)
   {
       long seconds = inDate / 1000;
       // Is it not suitable to cache?
       if (seconds<_lastSeconds ||
           _lastSeconds>0 && seconds>_lastSeconds+__hitWindow)
       {
           // It"s a cache miss
           _misses++;
           if (_misses<__MaxMisses)
           {
               Date d = new Date(inDate);
               return _tzFormat.format(d);
           }    
       }
       else if (_misses>0)
           _misses--;
                                         
       // Check if we are in the same second
       // and don"t care about millis
       if (_lastSeconds==seconds && !_millis)
           return _lastResult;
       Date d = new Date(inDate);
       
       // Check if we need a new format string
       long minutes = seconds/60;
       if (_lastMinutes != minutes)
       {
           _lastMinutes = minutes;
           _secFormatString=_minFormat.format(d);
           int i;
           int l;
           if (_millis)
           {
               i=_secFormatString.indexOf("ss.SSS");
               l=6;
           }
           else
           {
               i=_secFormatString.indexOf("ss");
               l=2;
           }
           _secFormatString0=_secFormatString.substring(0,i);
           _secFormatString1=_secFormatString.substring(i+l);
       }
       // Always format if we get here
       _lastSeconds = seconds;
       StringBuffer sb=new StringBuffer(_secFormatString.length());
       synchronized(sb)
       {
           sb.append(_secFormatString0);
           int s=(int)(seconds%60);
           if (s<10)
               sb.append("0");
           sb.append(s);
           if (_millis)
           {
               long millis = inDate%1000;
               if (millis<10)
                   sb.append(".00");
               else if (millis<100)
                   sb.append(".0");
               else
                   sb.append(".");
               sb.append(millis);
           }
           sb.append(_secFormatString1);
           _lastResult=sb.toString();
       }
               
       return _lastResult;
   }
   /* ------------------------------------------------------------ */
   /** Format to string buffer. 
    * @param inDate Date the format
    * @param buffer StringBuffer
    */
   public void format(long inDate, StringBuffer buffer)
   {
       buffer.append(format(inDate));
   }
   
   /* ------------------------------------------------------------ */
   /** Get the format.
    */
   public SimpleDateFormat getFormat()
   {
       return _minFormat;
   }
   /* ------------------------------------------------------------ */
   public String getFormatString()
   {
       return _formatString;
   }    
   /* ------------------------------------------------------------ */
   public String now()
   {
       return format(System.currentTimeMillis());
   }

}


 </source>
   
  
 
  



Date format: "dd.MM.yy", "yyyy.MM.dd G "at" hh:mm:ss z","EEE, MMM d, ""yy", "h:mm a", "H:mm", "H:mm:ss:SSS", "K:mm a,z","yyyy.MMMMM.dd GGG hh:mm aaa"

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class SimpleDateFormatDemo {

 static public void displayDate(Locale currentLocale) {
   Date today;
   String result;
   SimpleDateFormat formatter;
   formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
   today = new Date();
   result = formatter.format(today);
   System.out.println("Locale: " + currentLocale.toString());
   System.out.println("Result: " + result);
 }
 static public void displayPattern(String pattern, Locale currentLocale) {
   Date today;
   SimpleDateFormat formatter;
   String output;
   formatter = new SimpleDateFormat(pattern, currentLocale);
   today = new Date();
   output = formatter.format(today);
   System.out.println(pattern + "   " + output);
 }
 static public void main(String[] args) {
   Locale[] locales = { new Locale("fr", "FR"), new Locale("de", "DE"),
       new Locale("en", "US") };
   for (int i = 0; i < locales.length; i++) {
     displayDate(locales[i]);
     System.out.println();
   }
   String[] patterns = { "dd.MM.yy", "yyyy.MM.dd G "at" hh:mm:ss z",
       "EEE, MMM d, ""yy", "h:mm a", "H:mm", "H:mm:ss:SSS", "K:mm a,z",
       "yyyy.MMMMM.dd GGG hh:mm aaa" };
   for (int k = 0; k < patterns.length; k++) {
     displayPattern(patterns[k], new Locale("en", "US"));
     System.out.println();
   }
   System.out.println();
 }

}



 </source>
   
  
 
  



DateFormat.getDateInstance(DateFormat.LONG)

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; class DateFormatDemo {

 public static void main(String args[]) {
   Date date = new Date();
   DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
   System.out.println("Long form: " + df.format(date));
 }

}


 </source>
   
  
 
  



DateFormat.getDateInstance(DateFormat.SHORT)

   <source lang="java">
   

import java.text.DateFormat; import java.text.ParseException; import java.util.Date; public class DateTest {

 public static void main(String[] args) throws ParseException {
   DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
   formatter.setLenient(false);
   Date theDate = formatter.parse(args[0]);
   System.out.println(theDate);
 }

}



 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA).format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA).format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA).format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA).format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.LONG)

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; class DateFormatDemo {

 public static void main(String args[]) {
   Date date = new Date();
   DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG);
   System.out.println("Long form: " + df.format(date));
 }

}


 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.LONG, Locale.CANADA).format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CANADA).format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA).format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA).format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



DateFormat.getTimeInstance(DateFormat.SHORT)

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; class DateFormatDemo {

 public static void main(String args[]) {
   Date date = new Date();
   DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
   System.out.println("Short form: " + df.format(date));
 }

}


 </source>
   
  
 
  



DateFormat.SHORT

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
   System.out.println(strDate);
 }

}



 </source>
   
  
 
  



Date Format Symbols

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateFormatSymbolsDemo {

 static public void changeWeekDays() {
   Date today;
   String result;
   SimpleDateFormat formatter;
   DateFormatSymbols symbols;
   String[] defaultDays;
   String[] modifiedDays;
   symbols = new DateFormatSymbols(new Locale("en", "US"));
   defaultDays = symbols.getShortWeekdays();
   for (int i = 0; i < defaultDays.length; i++) {
     System.out.print(defaultDays[i] + "  ");
   }
   System.out.println();
   String[] capitalDays = { "", "SUN", "MON", "TUE", "WED", "THU", "FRI",
       "SAT" };
   symbols.setShortWeekdays(capitalDays);
   modifiedDays = symbols.getShortWeekdays();
   for (int i = 0; i < modifiedDays.length; i++) {
     System.out.print(modifiedDays[i] + "  ");
   }
   System.out.println();
   System.out.println();
   formatter = new SimpleDateFormat("E", symbols);
   today = new Date();
   result = formatter.format(today);
   System.out.println(result);
 }
 static public void main(String[] args) {
   changeWeekDays();
 }

}



 </source>
   
  
 
  



Date Formatting and Localization

   <source lang="java">
   

import java.text.DateFormat; import java.text.SimpleDateFormat; public class Main {

 public static void main(String[] args) {
   DateFormat df = DateFormat.getDateInstance();
   if (df instanceof SimpleDateFormat) {
     SimpleDateFormat sdf = (SimpleDateFormat) df;
     System.out.println(sdf.toPattern());
   } else {
     System.out.println("sorry");
   }
 }

}



 </source>
   
  
 
  



Date format viewer

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; import java.util.Locale; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; public class DateViewer extends JPanel {

 protected AbstractTableModel tableModel;
 protected Date selectedDate = new Date();
 protected final static Locale[] availableLocales;
 static {
   availableLocales = Locale.getAvailableLocales();
 }
 public final static int LOCALE_COLUMN = 0;
 public final static int SHORT_COLUMN = 1;
 public final static int MEDIUM_COLUMN = 2;
 public final static int LONG_COLUMN = 3;
 public final static int FULL_COLUMN = 4;
 public final static String[] columnHeaders = { "Locale", "Short", "Medium", "Long", "Full" };
 public static void main(String[] args) {
   JFrame f = new JFrame("Date Viewer");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.getContentPane().add(new DateViewer());
   f.pack();
   f.setVisible(true);
 }
 public DateViewer() {
   tableModel = new LocaleTableModel();
   JTable table = new JTable(tableModel);
   add(new JScrollPane(table));
   refreshTable();
 }
 protected void refreshTable() {
   int style = DateFormat.SHORT;
   selectedDate = new Date();
   tableModel.fireTableDataChanged();
 }
 class LocaleTableModel extends AbstractTableModel {
   public int getRowCount() {
     return availableLocales.length;
   }
   public int getColumnCount() {
     return columnHeaders.length;
   }
   public Object getValueAt(int row, int column) {
     Locale locale = availableLocales[row];
     DateFormat formatter = DateFormat.getInstance();
     switch (column) {
     case LOCALE_COLUMN:
       return locale.getDisplayName();
     case SHORT_COLUMN:
       formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
       break;
     case MEDIUM_COLUMN:
       formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
       break;
     case LONG_COLUMN:
       formatter = DateFormat.getDateInstance(DateFormat.LONG, locale);
       break;
     case FULL_COLUMN:
       formatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
     }
     return formatter.format(selectedDate);
   }
   public String getColumnName(int column) {
     return columnHeaders[column];
   }
 }

}



 </source>
   
  
 
  



Date Format with Locale

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class DateFormatDemo {

 static public void displayDate(Locale currentLocale) {
   Date today;
   String dateOut;
   DateFormat dateFormatter;
   dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT,
       currentLocale);
   today = new Date();
   dateOut = dateFormatter.format(today);
   System.out.println(dateOut + "   " + currentLocale.toString());
 }
 static public void showBothStyles(Locale currentLocale) {
   Date today;
   String result;
   DateFormat formatter;
   int[] styles = { DateFormat.DEFAULT, DateFormat.SHORT, DateFormat.MEDIUM,
       DateFormat.LONG, DateFormat.FULL };
   System.out.println();
   System.out.println("Locale: " + currentLocale.toString());
   System.out.println();
   today = new Date();
   for (int k = 0; k < styles.length; k++) {
     formatter = DateFormat.getDateTimeInstance(styles[k], styles[k],
         currentLocale);
     result = formatter.format(today);
     System.out.println(result);
   }
 }
 static public void showDateStyles(Locale currentLocale) {
   Date today = new Date();
   String result;
   DateFormat formatter;
   int[] styles = { DateFormat.DEFAULT, DateFormat.SHORT, DateFormat.MEDIUM,
       DateFormat.LONG, DateFormat.FULL };
   System.out.println();
   System.out.println("Locale: " + currentLocale.toString());
   System.out.println();
   for (int k = 0; k < styles.length; k++) {
     formatter = DateFormat.getDateInstance(styles[k], currentLocale);
     result = formatter.format(today);
     System.out.println(result);
   }
 }
 static public void showTimeStyles(Locale currentLocale) {
   Date today = new Date();
   String result;
   DateFormat formatter;
   int[] styles = { DateFormat.DEFAULT, DateFormat.SHORT, DateFormat.MEDIUM,
       DateFormat.LONG, DateFormat.FULL };
   System.out.println();
   System.out.println("Locale: " + currentLocale.toString());
   System.out.println();
   for (int k = 0; k < styles.length; k++) {
     formatter = DateFormat.getTimeInstance(styles[k], currentLocale);
     result = formatter.format(today);
     System.out.println(result);
   }
 }
 static public void main(String[] args) {
   Locale[] locales = { new Locale("fr", "FR"), new Locale("de", "DE"),
       new Locale("en", "US") };
   for (int i = 0; i < locales.length; i++) {
     displayDate(locales[i]);
   }
   showDateStyles(new Locale("en", "US"));
   showDateStyles(new Locale("fr", "FR"));
   showTimeStyles(new Locale("en", "US"));
   showTimeStyles(new Locale("de", "DE"));
   showBothStyles(new Locale("en", "US"));
   showBothStyles(new Locale("fr", "FR"));
 }

}



 </source>
   
  
 
  



Decimal Format with different Symbols

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; public class DecimalFormatDemo {

 static public void customFormat(String pattern, double value) {
   DecimalFormat myFormatter = new DecimalFormat(pattern);
   String output = myFormatter.format(value);
   System.out.println(value + "  " + pattern + "  " + output);
 }
 static public void localizedFormat(String pattern, double value, Locale loc) {
   NumberFormat nf = NumberFormat.getNumberInstance(loc);
   DecimalFormat df = (DecimalFormat) nf;
   df.applyPattern(pattern);
   String output = df.format(value);
   System.out.println(pattern + "  " + output + "  " + loc.toString());
 }
 static public void main(String[] args) {
   customFormat("###,###.###", 123456.789);
   customFormat("###.##", 123456.789);
   customFormat("000000.000", 123.78);
   customFormat("$###,###.###", 12345.67);
   customFormat("\u00a5###,###.###", 12345.67);
   Locale currentLocale = new Locale("en", "US");
   DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(
       currentLocale);
   unusualSymbols.setDecimalSeparator("|");
   unusualSymbols.setGroupingSeparator("^");
   String strange = "#,##0.###";
   DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
   weirdFormatter.setGroupingSize(4);
   String bizarre = weirdFormatter.format(12345.678);
   System.out.println(bizarre);
   Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"),
       new Locale("fr", "FR") };
   for (int i = 0; i < locales.length; i++) {
     localizedFormat("###,###.###", 123456.789, locales[i]);
   }
 }

}



 </source>
   
  
 
  



Display complete time and date information

   <source lang="java">
    

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt = new Formatter();
   fmt.format("%tc", cal);
   System.out.println(fmt);
 }

} //Wed Jun 11 10:39:58 PDT 2008



 </source>
   
  
 
  



Display just hour and minute

   <source lang="java">
    

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt = new Formatter();
   fmt.format("%tl:%tM", cal, cal);
   System.out.println(fmt);
 }

} //10:40



 </source>
   
  
 
  



Display month by name and number

   <source lang="java">
    

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt = new Formatter();
   fmt.format("%tB %tb %tm", cal, cal, cal);
   System.out.println(fmt);
 }

} //June Jun 06



 </source>
   
  
 
  



Display standard 12-hour time format

   <source lang="java">
    

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt.format("%tr", cal);
   System.out.println(fmt);
 }

} //10:39:33 AM



 </source>
   
  
 
  



Find the current date format

   <source lang="java">
  

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; public class Main {

 public static void main(String args[]) {
   SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT);
   System.out.println("The short date format is  " + df.toPattern());
   Locale loc = Locale.ITALY;
   df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, loc);
   System.out.println("The short date format is  " + df.toPattern());
 }

}


 </source>
   
  
 
  



Format date in dd/mm/yyyy format

   <source lang="java">
   

import java.util.Date; import java.text.SimpleDateFormat; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
   String strDate = sdf.format(date);
   System.out.println("formatted date in mm/dd/yy : " + strDate);
   
   sdf = new SimpleDateFormat("dd/MM/yyyy");
   strDate = sdf.format(date);
   System.out.println("formatted date in dd/MM/yyyy : " + strDate);
 }

}



 </source>
   
  
 
  



Format date in Default format

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDate = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
   System.out.println(strDate);
 }

}



 </source>
   
  
 
  



Format date in Full format

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   String strDate = DateFormat.getDateInstance(DateFormat.FULL).format(date);
   System.out.println(strDate);
 }

}



 </source>
   
  
 
  



Format date in Long format

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDate = DateFormat.getDateInstance(DateFormat.LONG).format(date);
   System.out.println(strDate);
 }

}



 </source>
   
  
 
  



Format date in Medium format

   <source lang="java">
   

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
   System.out.println(strDate);
 }

}



 </source>
   
  
 
  



Format date in mm-dd-yyyy hh:mm:ss format

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
   String strDate = sdf.format(date);
   System.out.println("formatted date in mm/dd/yy : " + strDate);
   sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
   strDate = sdf.format(date);
   System.out.println("formatted date in mm-dd-yyyy hh:mm:ss : " + strDate);
 }

}



 </source>
   
  
 
  



format Duration

   <source lang="java">
  

import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public abstract class TimeUtils {

   public static String formatDuration(long duration) {
       SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss:SSS");
       format.setTimeZone(TimeZone.getTimeZone("GMT"));
       return format.format(new Date(duration));
   }

}


 </source>
   
  
 
  



Format hour in H (0-23) format like 0, 1...23.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("H");
   System.out.println("hour in H format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in h (1-12 in AM/PM) format like 1, 2..12.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   String strDateFormat = "h";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println("hour in h format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in HH (00-23) format like 00, 01..23.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   
   SimpleDateFormat sdf = new SimpleDateFormat("HH");
   System.out.println("hour in HH format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in hh (01-12 in AM/PM) format like 01, 02..12.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("hh");
   System.out.println("hour in hh format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in K (0-11 in AM/PM) format like 0, 1..11.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   
   SimpleDateFormat sdf = new SimpleDateFormat("K");
   System.out.println("hour in K format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in k (1-24) format like 1, 2..24.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("k");
   System.out.println("hour in k format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format hour in KK (00-11) format like 00, 01,..11.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("KK");
   System.out.println("hour in KK format : " + sdf.format(date));
 }

} // hour in h format : 11



 </source>
   
  
 
  



Format hour in kk (01-24) format like 01, 02..24.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("kk");
   System.out.println("hour in kk format : " + sdf.format(date));
 }

} //hour in h format : 11



 </source>
   
  
 
  



Format minutes in mm format like 01, 02 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("mm");
   System.out.println("minutes in mm format : " + sdf.format(date));
 }

} // minutes in m format : 35



 </source>
   
  
 
  



Format month in M format like 1,2 etc

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("M");
   System.out.println("Current Month in M format : " + sdf.format(date));
 }

} //Current Month in M format : 2



 </source>
   
  
 
  



Format Month in MM format like 01, 02 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat  sdf = new SimpleDateFormat("MM");
   System.out.println("Current Month in MM format : " + sdf.format(date));  }

} //Current Month in M format : 02



 </source>
   
  
 
  



Format Month in MMM format like Jan, Feb etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("MMM");
   System.out.println("Current Month in MMM format : " + sdf.format(date));
   }

} //Current Month in MMM format : Feb



 </source>
   
  
 
  



Format Month in MMMM format like January, February etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
   System.out.println("Current Month in MMMM format : " + sdf.format(date));
   
   }

} //Current Month in MMMM format : February



 </source>
   
  
 
  



Format seconds in s format like 1,2 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("s");
   System.out.println("seconds in s format : " + sdf.format(date));
 }

} //seconds in s format : 40



 </source>
   
  
 
  



Format seconds in ss format like 01, 02 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("ss");
   System.out.println("seconds in ss format : " + sdf.format(date));
 }

} //seconds in ss format : 14



 </source>
   
  
 
  



Formatting day in dd format like 01, 02 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   String strDateFormat = "dd";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println("Current day in dd format : " + sdf.format(new Date()));
 }

}



 </source>
   
  
 
  



Formatting day in d format like 1,2 etc

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDateFormat = "d";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println("Current day in d format : " + sdf.format(date));
 }

}



 </source>
   
  
 
  



Formatting day of week in EEEE format like Sunday, Monday etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   
   String strDateFormat = "EEEE";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println("Current day of week in EEEE format : " + sdf.format(new Date()));
 }

}



 </source>
   
  
 
  



Formatting day of week using SimpleDateFormat

   <source lang="java">
   

//Formatting day of week in E format like Sun, Mon etc. import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   String strDateFormat = "E";
   SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
   System.out.println("Current day of week in E format : " + sdf.format(date));
 }

}



 </source>
   
  
 
  



Formatting minute in m format like 1,2 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   
   SimpleDateFormat sdf = new SimpleDateFormat("m");
   System.out.println("minutes in m format : " + sdf.format(date));
 }

} //minutes in m format : 35



 </source>
   
  
 
  



Format year in yy format like 07, 08 etc

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yy");
   System.out.println("Current year in yy format : " + sdf.format(date));
 }

} //Current year in yy format : 09



 </source>
   
  
 
  



Format year in yyyy format like 2007, 2008 etc.

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
   System.out.println("Current year in yyyy format : " + sdf.format(date));
 }

} //Current year in yyyy format : 2009



 </source>
   
  
 
  



Full day name: SimpleDateFormat("EEEE")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("EEEE"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Full length of month name: SimpleDateFormat("MMMM")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("MMMM"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Get a List of Short Month Names

   <source lang="java">
  

import java.text.DateFormatSymbols; public class Main {

 public static void main(String[] args) {
   String[] shortMonths = new DateFormatSymbols().getShortMonths();
   for (int i = 0; i < shortMonths.length; i++) {
     String shortMonth = shortMonths[i];
     System.out.println("shortMonth = " + shortMonth);
   }
 }

}


 </source>
   
  
 
  



Get a List of Short Weekday Names

   <source lang="java">
  

import java.text.DateFormatSymbols; public class Main {

 public static void main(String[] args) {
   String[] shortWeekdays = new DateFormatSymbols().getShortWeekdays();
   for (int i = 0; i < shortWeekdays.length; i++) {
     String shortWeekday = shortWeekdays[i];
     System.out.println("shortWeekday = " + shortWeekday);
   }
 }

}



 </source>
   
  
 
  



Get a List of Weekday Names

   <source lang="java">
  

import java.text.DateFormatSymbols; public class Main {

 public static void main(String[] args) {
   String[] weekdays = new DateFormatSymbols().getWeekdays();
   for (int i = 0; i < weekdays.length; i++) {
     String weekday = weekdays[i];
     System.out.println("weekday = " + weekday);
   }
 }

}


 </source>
   
  
 
  



Get Date Suffix

   <source lang="java">
 

/**********************************************************************************

   Feedzeo! 
   A free and open source RSS/Atom/RDF feed aggregator
   Copyright (C) 2005-2006  Anand Rao (anandrao@users.sourceforge.net)
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
                                                                                                                                                                        • /

import java.util.*; public class DateUtil {

  private static String[] Months= { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  private static String getDateSuffix( int i) { 
       switch (i) {
           case 1: case 21: case 31:
                  return ("st");
           case 2: case 22: 
                  return ("nd");
           case 3: case 23:
                  return ("rd");
           case 4: case 5:
           case 6: case 7:
           case 8: case 9:
           case 10: case 11:
           case 12: case 13:
           case 14: case 15:
           case 16: case 17:
           case 18: case 19:
           case 20: case 24:
           case 25: case 26:
           case 27: case 28:
           case 29: case 30:
                 return ("th");
           default:
                  return ("");
       }
  }

}


 </source>
   
  
 
  



ISO8601 Date Format

   <source lang="java">
 

//revised from skaringa

import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /**

* Format and parse an ISO 8601 DateFormat used in XML documents.
* The lexical representation for date is the reduced (right truncated)
* lexical representation for dateTime: CCYY-MM-DD.
* No left truncation is allowed.
* An optional following time zone qualifier is allowed as for dateTime.
*/

public class ISO8601DateFormat extends ISO8601DateTimeFormat {

 /**
  * Construct a new ISO8601DateFormat using the default time zone.
  *
  */
 public ISO8601DateFormat() {
   setCalendar(Calendar.getInstance());
 }
 /**
  * Construct a new ISO8601DateFormat using a specific time zone.
  * @param tz The time zone used to format and parse the date.
  */
 public ISO8601DateFormat(TimeZone tz) {
   setCalendar(Calendar.getInstance(tz));
 }
 /**
  * @see java.text.DateFormat#parse(String, ParsePosition)
  */
 public Date parse(String text, ParsePosition pos) {
   int i = pos.getIndex();
   try {
     int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
     i += 4;
     if (text.charAt(i) != "-") {
       throw new NumberFormatException();
     }
     i++;
     int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
     i += 2;
     if (text.charAt(i) != "-") {
       throw new NumberFormatException();
     }
     i++;
     int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
     i += 2;
     calendar.set(year, month, day);
     calendar.set(Calendar.HOUR_OF_DAY, 0);
     calendar.set(Calendar.MINUTE, 0);
     calendar.set(Calendar.SECOND, 0);
     calendar.set(Calendar.MILLISECOND, 0); // no parts of a second
     i = parseTZ(i, text);
   }
   catch (NumberFormatException ex) {
     pos.setErrorIndex(i);
     return null;
   }
   catch (IndexOutOfBoundsException ex) {
     pos.setErrorIndex(i);
     return null;
   }
   finally {
     pos.setIndex(i);
   }
   return calendar.getTime();
 }
 /**
  * @see java.text.DateFormat#format(Date, StringBuffer, FieldPosition)
  */
 public StringBuffer format(
   Date date,
   StringBuffer sbuf,
   FieldPosition fieldPosition) {
   calendar.setTime(date);
   writeCCYYMM(sbuf);
   //writeTZ(sbuf);
   return sbuf;
 }

}

/**

* Format and parse an ISO 8601 DateTimeFormat used in XML documents.
* This lexical representation is the ISO 8601
* extended format CCYY-MM-DDThh:mm:ss
* where "CC" represents the century, "YY" the year, "MM" the month
* and "DD" the day,
* preceded by an optional leading "-" sign to indicate a negative number.
* If the sign is omitted, "+" is assumed.
* The letter "T" is the date/time separator
* and "hh", "mm", "ss" represent hour, minute and second respectively.
* This representation may be immediately followed by a "Z" to indicate
* Coordinated Universal Time (UTC) or, to indicate the time zone,
* i.e. the difference between the local time and Coordinated Universal Time,
* immediately followed by a sign, + or -,
* followed by the difference from UTC represented as hh:mm.
*
*/
class ISO8601DateTimeFormat extends DateFormat {
 /**
  * Construct a new ISO8601DateTimeFormat using the default time zone.
  *
  */
 public ISO8601DateTimeFormat() {
   setCalendar(Calendar.getInstance());
 }
 /**
  * Construct a new ISO8601DateTimeFormat using a specific time zone.
  * @param tz The time zone used to format and parse the date.
  */
 public ISO8601DateTimeFormat(TimeZone tz) {
   setCalendar(Calendar.getInstance(tz));
 }
 /**
  * @see DateFormat#parse(String, ParsePosition)
  */
 public Date parse(String text, ParsePosition pos) {
   int i = pos.getIndex();
   try {
     int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
     i += 4;
     if (text.charAt(i) != "-") {
       throw new NumberFormatException();
     }
     i++;
     int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
     i += 2;
     if (text.charAt(i) != "-") {
       throw new NumberFormatException();
     }
     i++;
     int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
     i += 2;
     if (text.charAt(i) != "T") {
       throw new NumberFormatException();
     }
     i++;
     int hour = Integer.valueOf(text.substring(i, i + 2)).intValue();
     i += 2;
     if (text.charAt(i) != ":") {
       throw new NumberFormatException();
     }
     i++;
     int mins = Integer.valueOf(text.substring(i, i + 2)).intValue();
     i += 2;
     int secs = 0;
     if (i < text.length() && text.charAt(i) == ":") {
       // handle seconds flexible
       i++;
       secs = Integer.valueOf(text.substring(i, i + 2)).intValue();
       i += 2;
     }
     calendar.set(year, month, day, hour, mins, secs);
     calendar.set(Calendar.MILLISECOND, 0); // no parts of a second
     i = parseTZ(i, text);
   }
   catch (NumberFormatException ex) {
     pos.setErrorIndex(i);
     return null;
   }
   catch (IndexOutOfBoundsException ex) {
     pos.setErrorIndex(i);
     return null;
   }
   finally {
     pos.setIndex(i);
   }
   return calendar.getTime();
 }
 /**
  * Parse the time zone.
  * @param i The position to start parsing.
  * @param text The text to parse.
  * @return The position after parsing has finished.
  */
 protected final int parseTZ(int i, String text) {
   if (i < text.length()) {
     // check and handle the zone/dst offset
     int offset = 0;
     if (text.charAt(i) == "Z") {
       offset = 0;
       i++;
     }
     else {
       int sign = 1;
       if (text.charAt(i) == "-") {
         sign = -1;
       }
       else if (text.charAt(i) != "+") {
         throw new NumberFormatException();
       }
       i++;
       int offsetHour = Integer.valueOf(text.substring(i, i + 2)).intValue();
       i += 2;
       if (text.charAt(i) != ":") {
         throw new NumberFormatException();
       }
       i++;
       int offsetMin = Integer.valueOf(text.substring(i, i + 2)).intValue();
       i += 2;
       offset = ((offsetHour * 60) + offsetMin) * 60000 * sign;
     }
     int offsetCal =
       calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
     calendar.add(Calendar.MILLISECOND, offsetCal - offset);
   }
   return i;
 }
 /**
  * @see DateFormat#format(Date, StringBuffer, FieldPosition)
  */
 public StringBuffer format(
   Date date,
   StringBuffer sbuf,
   FieldPosition fieldPosition) {
   calendar.setTime(date);
   writeCCYYMM(sbuf);
   sbuf.append("T");
   writehhmmss(sbuf);
   writeTZ(sbuf);
   return sbuf;
 }
 /**
  * Write the time zone string.
  * @param sbuf The buffer to append the time zone.
  */
 protected final void writeTZ(StringBuffer sbuf) {
   int offset =
     calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
   if (offset == 0) {
     sbuf.append("Z");
   }
   else {
     int offsetHour = offset / 3600000;
     int offsetMin = (offset % 3600000) / 60000;
     if (offset >= 0) {
       sbuf.append("+");
     }
     else {
       sbuf.append("-");
       offsetHour = 0 - offsetHour;
       offsetMin = 0 - offsetMin;
     }
     appendInt(sbuf, offsetHour, 2);
     sbuf.append(":");
     appendInt(sbuf, offsetMin, 2);
   }
 }
 /**
  * Write hour, minutes, and seconds.
  * @param sbuf The buffer to append the string.
  */
 protected final void writehhmmss(StringBuffer sbuf) {
   int hour = calendar.get(Calendar.HOUR_OF_DAY);
   appendInt(sbuf, hour, 2);
   sbuf.append(":");
   int mins = calendar.get(Calendar.MINUTE);
   appendInt(sbuf, mins, 2);
   sbuf.append(":");
   int secs = calendar.get(Calendar.SECOND);
   appendInt(sbuf, secs, 2);
 }
 /**
  * Write century, year, and months.
  * @param sbuf The buffer to append the string.
  */
 protected final void writeCCYYMM(StringBuffer sbuf) {
   int year = calendar.get(Calendar.YEAR);
   appendInt(sbuf, year, 4);
   String month;
   switch (calendar.get(Calendar.MONTH)) {
     case Calendar.JANUARY :
       month = "-01-";
       break;
     case Calendar.FEBRUARY :
       month = "-02-";
       break;
     case Calendar.MARCH :
       month = "-03-";
       break;
     case Calendar.APRIL :
       month = "-04-";
       break;
     case Calendar.MAY :
       month = "-05-";
       break;
     case Calendar.JUNE :
       month = "-06-";
       break;
     case Calendar.JULY :
       month = "-07-";
       break;
     case Calendar.AUGUST :
       month = "-08-";
       break;
     case Calendar.SEPTEMBER :
       month = "-09-";
       break;
     case Calendar.OCTOBER :
       month = "-10-";
       break;
     case Calendar.NOVEMBER :
       month = "-11-";
       break;
     case Calendar.DECEMBER :
       month = "-12-";
       break;
     default :
       month = "-NA-";
       break;
   }
   sbuf.append(month);
   int day = calendar.get(Calendar.DAY_OF_MONTH);
   appendInt(sbuf, day, 2);
 }
 /**
  * Write an integer value with leading zeros.
  * @param buf The buffer to append the string.
  * @param value The value to write.
  * @param length The length of the string to write.
  */
 protected final void appendInt(StringBuffer buf, int value, int length) {
   int len1 = buf.length();
   buf.append(value);
   int len2 = buf.length();
   for (int i = len2; i < len1 + length; ++i) {
     buf.insert(len1, "0");
   }
 }

}


 </source>
   
  
 
  



ISO8601 formatter for date-time without time zone.The format used is yyyy-MM-dd"T"HH:mm:ss.

   <source lang="java">
   

import java.util.Date; import org.apache.rumons.lang.time.DateFormatUtils; public class Main {

 public static void main(String[] args) {
   Date today = new Date();
   String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(today);
   System.out.println("timestamp = " + timestamp);
 }

}



 </source>
   
  
 
  



ISO8601 formatter for date-time with time zone. The format used is yyyy-MM-dd"T"HH:mm:ssZZ.

   <source lang="java">
   

import java.util.Date; import org.apache.rumons.lang.time.DateFormatUtils; public class Main {

 public static void main(String[] argv) throws Exception {
   Date today = new Date();
   String timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(today);
   System.out.println("timestamp = " + timestamp);
 }

}



 </source>
   
  
 
  



Java SimpleDateFormat Class Example("MM/dd/yyyy")

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String args[]) {
   Date date = new Date();
   String DATE_FORMAT = "MM/dd/yyyy";
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   System.out.println("Today is " + sdf.format(date));
 }

}



 </source>
   
  
 
  



new SimpleDateFormat("a"): The am/pm marker

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("a"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("hh")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("hh");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("HH.mm.ss")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("HH.mm.ss");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("hh:mm:ss a")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Date date = new Date();
   Format formatter = new SimpleDateFormat("hh:mm:ss a");
   String s = formatter.format(date);
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("HH:mm:ss Z")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("HH:mm:ss Z");
   Date date = (Date) formatter.parseObject("22:14:02 -0500");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("H") // The hour (0-23)

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("H");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("mm")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("mm");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("m"): The minutes

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("m");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("ss")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("ss");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("s"): The seconds

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("s"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("Z")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("Z"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("z"): The time zone

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("z"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



new SimpleDateFormat("zzzz")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("zzzz"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Parse a date and time

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
   Date date = (Date) formatter.parseObject("2002.01.29.08.36.33");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



Parse date string input with DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA)

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   Date date = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA).parse("21.33.03");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



Parse string date value input with SimpleDateFormat("dd-MMM-yy")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("dd-MMM-yy");
   Date date = (Date) formatter.parseObject("29-Jan-02");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



Parse string date value input with SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
   Date date = (Date) formatter.parseObject("Tue, 29 Jan 2004 21:14:02 -0500");
 }

}


 </source>
   
  
 
  



Parse string date value with default format: DateFormat.getDateInstance(DateFormat.DEFAULT)

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Date date = DateFormat.getDateInstance(DateFormat.DEFAULT).parse("Feb 28, 2002");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



Parse with a custom format

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("E, dd MMM yyyy", Locale.CANADA);
   Date date = (Date) formatter.parseObject("mar., 29 janv. 2002");
 }

}


 </source>
   
  
 
  



Parse with a default format

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] argv) throws Exception {
   Date date = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CANADA).parse("29 janv. 2002");
 }

}


 </source>
   
  
 
  



Parsing custom formatted date string into Date object using SimpleDateFormat

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) throws Exception {
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
   Date date = sdf.parse("31/12/06");
   System.out.println(date);
 }

} //Sun Dec 31 00:00:00 PST 2006



 </source>
   
  
 
  



Parsing the Time Using a Custom Format

   <source lang="java">
  

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   DateFormat formatter = new SimpleDateFormat("hh.mm.ss a");
   Date date = (Date) formatter.parse("02.47.44 PM");
   System.out.println(date);
 }

}


 </source>
   
  
 
  



Returns a String in the format Xhrs, Ymins, Z sec, for the time difference between two times

   <source lang="java">
  

/**

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.Collection;

/**

* General string utils
*/

public class StringUtils {

 final public static char COMMA = ",";
 final public static String COMMA_STR = ",";
 final public static char ESCAPE_CHAR = "\\";
 private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
 
 /**
  * 
  * Given a finish and start time in long milliseconds, returns a 
  * String in the format Xhrs, Ymins, Z sec, for the time difference between two times. 
  * If finish time comes before start time then negative valeus of X, Y and Z wil return. 
  * 
  * @param finishTime finish time
  * @param startTime start time
  */
 public static String formatTimeDiff(long finishTime, long startTime){
   StringBuffer buf = new StringBuffer();
   
   long timeDiff = finishTime - startTime; 
   long hours = timeDiff / (60*60*1000);
   long rem = (timeDiff % (60*60*1000));
   long minutes =  rem / (60*1000);
   rem = rem % (60*1000);
   long seconds = rem / 1000;
   
   if (hours != 0){
     buf.append(hours);
     buf.append("hrs, ");
   }
   if (minutes != 0){
     buf.append(minutes);
     buf.append("mins, ");
   }
   // return "0sec if no difference
   buf.append(seconds);
   buf.append("sec");
   return buf.toString(); 
 }

}


 </source>
   
  
 
  



SimpleDateFormat("dd-MMM-yy")

   <source lang="java">
  


import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("dd-MMM-yy");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Simple Date Format Demo

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.Color; import java.awt.ruponent; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SimpleDateFormatDemo extends JPanel {

 static JFrame frame;
 JLabel result;
 String currentPattern;
 Date today;
 LocaleGroup availableLocales;
 public SimpleDateFormatDemo() {
   today = new Date();
   availableLocales = new LocaleGroup();
   String[] patternExamples = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
       "yyyy.MM.dd G "at" hh:mm:ss z", "EEE, MMM d, ""yy", "h:mm a",
       "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" };
   currentPattern = patternExamples[0];
   // Set up the UI for selecting a pattern.
   JLabel patternLabel1 = new JLabel("Enter the pattern string or");
   JLabel patternLabel2 = new JLabel("select one from the list:");
   patternLabel1.setAlignmentX(Component.LEFT_ALIGNMENT);
   patternLabel2.setAlignmentX(Component.LEFT_ALIGNMENT);
   JComboBox patternList = new JComboBox(patternExamples);
   patternList.setSelectedIndex(0);
   patternList.setEditable(true);
   patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
   PatternListener patternListener = new PatternListener();
   patternList.addActionListener(patternListener);
   // Set up the UI for selecting a locale.
   JLabel localeLabel = new JLabel("Select a Locale from the list:");
   localeLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
   JComboBox localeList = new JComboBox(availableLocales.getStrings());
   localeList.setSelectedIndex(0);
   localeList.setAlignmentX(Component.LEFT_ALIGNMENT);
   LocaleListener localeListener = new LocaleListener();
   localeList.addActionListener(localeListener);
   // Create the UI for displaying result
   JLabel resultLabel = new JLabel("Current Date and Time", JLabel.LEFT);
   resultLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
   result = new JLabel(" ");
   result.setForeground(Color.black);
   result.setAlignmentX(Component.LEFT_ALIGNMENT);
   result.setBorder(BorderFactory.createCompoundBorder(BorderFactory
       .createLineBorder(Color.black), BorderFactory.createEmptyBorder(5, 5,
       5, 5)));
   // Lay out everything
   JPanel patternPanel = new JPanel();
   patternPanel.setLayout(new BoxLayout(patternPanel, BoxLayout.Y_AXIS));
   patternPanel.add(patternLabel1);
   patternPanel.add(patternLabel2);
   patternPanel.add(patternList);
   JPanel localePanel = new JPanel();
   localePanel.setLayout(new BoxLayout(localePanel, BoxLayout.Y_AXIS));
   localePanel.add(localeLabel);
   localePanel.add(localeList);
   JPanel resultPanel = new JPanel();
   resultPanel.setLayout(new GridLayout(0, 1));
   resultPanel.add(resultLabel);
   resultPanel.add(result);
   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
   patternPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
   localePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
   resultPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
   add(patternPanel);
   add(Box.createVerticalStrut(10));
   add(localePanel);
   add(Box.createVerticalStrut(10));
   add(resultPanel);
   setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
   reformat();
 } // constructor
 /** Listens to the pattern combo box. */
 class PatternListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JComboBox cb = (JComboBox) e.getSource();
     String newSelection = (String) cb.getSelectedItem();
     currentPattern = newSelection;
     reformat();
   }
 }
 /** Listens to the locale combo box. */
 class LocaleListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JComboBox cb = (JComboBox) e.getSource();
     int index = cb.getSelectedIndex();
     availableLocales.setCurrent(index);
     reformat();
   }
 }
 /** Manages information about locales for this application. */
 class LocaleGroup {
   Locale currentLocale;
   Locale[] supportedLocales = { Locale.US, Locale.GERMANY, Locale.FRANCE
   // Add other locales here, if desired.
   };
   public LocaleGroup() {
     currentLocale = supportedLocales[0];
   }
   public void setCurrent(int index) {
     currentLocale = supportedLocales[index];
   }
   public Locale getCurrent() {
     return currentLocale;
   }
   public String[] getStrings() {
     String[] localeNames = new String[supportedLocales.length];
     for (int k = 0; k < supportedLocales.length; k++) {
       localeNames[k] = supportedLocales[k].getDisplayName();
     }
     return localeNames;
   }
 }
 /** Formats and displays today"s date. */
 public void reformat() {
   SimpleDateFormat formatter = new SimpleDateFormat(currentPattern,
       availableLocales.getCurrent());
   try {
     String dateString = formatter.format(today);
     result.setForeground(Color.black);
     result.setText(dateString);
   } catch (IllegalArgumentException iae) {
     result.setForeground(Color.red);
     result.setText("Error: " + iae.getMessage());
   }
 }
 public static void main(String s[]) {
   WindowListener l = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   frame = new JFrame("Date Formatting Demo");
   frame.addWindowListener(l);
   frame.getContentPane().add("Center", new SimpleDateFormatDemo());
   frame.pack();
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
   String s = formatter.format(new Date());
 }

}


 </source>
   
  
 
  



SimpleDateFormat.getAvailableLocales

   <source lang="java">
   

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.SimpleDateFormat; import java.util.Locale; public class Available {

 static public void main(String[] args) {
   Locale list[] = SimpleDateFormat.getAvailableLocales();
   for (int i = 0; i < list.length; i++) {
     System.out.println(list[i].toString());
   }
   for (int i = 0; i < list.length; i++) {
     System.out.println(list[i].getDisplayName());
   }
   for (int i = 0; i < list.length; i++) {
     System.out.println(list[i].getDisplayName(Locale.FRANCE));
   }
 }

}



 </source>
   
  
 
  



SimpleDateFormat("MM/dd/yy")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Date date = new Date();
   Format formatter = new SimpleDateFormat("MM/dd/yy");
   String s = formatter.format(date);
   System.out.println(s);
 }

}


 </source>
   
  
 
  



SimpleDateFormat("MM"): number based month value

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("MM");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



SimpleDateFormat("yyyy")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("yyyy"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Simply format a date as "YYYYMMDD"

   <source lang="java">
   

import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   GregorianCalendar gc = new GregorianCalendar();
   gc.setLenient(false);
   gc.set(GregorianCalendar.YEAR, 2003);
   gc.set(GregorianCalendar.MONTH, 12);
   gc.set(GregorianCalendar.DATE, 1);
   int m = gc.get(GregorianCalendar.MONTH) + 1;
   int d = gc.get(GregorianCalendar.DATE);
   String mm = Integer.toString(m);
   String dd = Integer.toString(d);
   System.out.println(gc.get(GregorianCalendar.YEAR) + (m < 10 ? "0" + mm : mm)
       + (d < 10 ? "0" + dd : dd));
 }

}



 </source>
   
  
 
  



The day in week: SimpleDateFormat("E")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("E"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



The day number: SimpleDateFormat("d")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("d"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale.

   <source lang="java">
   

import java.util.Date; import org.apache.rumons.lang.time.DateFormatUtils; public class Main {

 public static void main(String[] argv) throws Exception {
   Date today = new Date();
   String timestamp = DateFormatUtils.SMTP_DATETIME_FORMAT.format(today);
   System.out.println("timestamp = " + timestamp);
 }

}



 </source>
   
  
 
  



The month: SimpleDateFormat("M")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("M"); 
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



The Time and Date Format Suffixes

   <source lang="java">
    

Suffix Replaced By a Abbreviated weekday name A Full weekday name b Abbreviated month name B Full month name c Standard date and time string formatted as day month date hh::mm:ss tzone year C First two digits of year d Day of month as a decimal (01-31) D month/day/year e Day of month as a decimal (1-31) F year-month-day h Abbreviated month name H Hour (00 to 23) I Hour (01 to 12) j Day of year as a decimal (001 to 366) k Hour (0 to 23) l Hour (1 to 12) L Millisecond (000 to 999) m Month as decimal (01 to 13) M Minute as decimal (00 to 59) N Nanosecond (000000000 to 999999999) P Locale"s equivalent of AM or PM in uppercase p Locale"s equivalent of AM or PM in lowercase Q Milliseconds from 1/1/1970 r hh:mm (12-hour format) R hh:mm (24-hour format) S Seconds (00 to 60) s Seconds from 1/1/1970 UTC T hh:mm:ss (24-hour format) y Year in decimal without century (00 to 99) Y Year in decimal including century (0001 to 9999) z Offset from UTC Z Time zone name



 </source>
   
  
 
  



This is same as MEDIUM: DateFormat.getDateInstance(DateFormat.DEFAULT).format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



This is same as MEDIUM: DateFormat.getDateInstance().format(new Date())

   <source lang="java">
  

import java.text.DateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   String s = DateFormat.getDateInstance().format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Three letter-month value: SimpleDateFormat("MMM")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("MMM");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Time format viewer

   <source lang="java">
   

import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; public class TimeViewer extends JPanel {

 protected AbstractTableModel tableModel;
 protected Date selectedDate = new Date();
 protected final static Locale[] availableLocales;
 static {
   availableLocales = Locale.getAvailableLocales();
 }
 public final static int LOCALE_COLUMN = 0;
 public final static int SHORT_COLUMN = 1;
 public final static int MEDIUM_COLUMN = 2;
 public final static int LONG_COLUMN = 3;
 public final static int FULL_COLUMN = 4;
 public final static String[] columnHeaders = { "Locale", "Short", "Medium", "Long", "Full" };
 // Create the window for the Time viewer,
 // and make sure that later components will fit
 public static void main(String[] args) {
   JFrame f = new JFrame("Time Viewer");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.getContentPane().add(new TimeViewer());
   f.pack();
   f.setVisible(true);
 }
 public TimeViewer() {
   tableModel = new LocaleTableModel();
   JTable table = new JTable(tableModel);
   add(new JScrollPane(table));
   refreshTable();
 }
 protected void refreshTable() {
   int style = DateFormat.SHORT;
   DateFormat parser = DateFormat.getTimeInstance(style);
   selectedDate = new Date();
   tableModel.fireTableDataChanged();
 }
 class LocaleTableModel extends AbstractTableModel {
   public int getRowCount() {
     return availableLocales.length;
   }
   public int getColumnCount() {
     return columnHeaders.length;
   }
   public Object getValueAt(int row, int column) {
     Locale locale = availableLocales[row];
     DateFormat formatter = DateFormat.getInstance();
     switch (column) {
     case LOCALE_COLUMN:
       return locale.getDisplayName();
     case SHORT_COLUMN:
       formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
       break;
     case MEDIUM_COLUMN:
       formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
       break;
     case LONG_COLUMN:
       formatter = DateFormat.getTimeInstance(DateFormat.LONG, locale);
       break;
     case FULL_COLUMN:
       formatter = DateFormat.getTimeInstance(DateFormat.FULL, locale);
     }
     return formatter.format(selectedDate);
   }
   public String getColumnName(int column) {
     return columnHeaders[column];
   }
 }

}



 </source>
   
  
 
  



Two digits day number: SimpleDateFormat("dd")

   <source lang="java">
  

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] argv) throws Exception {
   Format formatter = new SimpleDateFormat("dd");
   String s = formatter.format(new Date());
   System.out.println(s);
 }

}


 </source>
   
  
 
  



Use relative indexes to simplify the creation of a custom time and date format.

   <source lang="java">
    

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt.format("Today is day %te of %<tB, %<tY", cal);
   System.out.println(fmt);
 }

} //Today is day 11 of June, 2008



 </source>