Parsing dates - top of Musings page

by Nick Duchon

This topic could really use some good examples!

Perhaps this will help.

I think the variables inside parseND, dfm, dfs and dfy, should be declared static, since they never change once they are instantiated.

// file: DateExample
// Date: Apr 23, 2011
// Author: Nicholas Duchon
// Purpose: demonstrate the Date and DateFormat classes

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class DateExample {
 public static void main (String args []) {

   String [] in = {"January 23, 1953", // medium
                   "Feb 1, 2011",      // medium
                   "12/13/2011",       // short
                   "3/14/2011",        // short
                   "1984",             // "Y"
                   "abc"};             // illegal, method returns null
  
  
  Date d = null;

   for (String s: in) {
       d = parseND (s);
       System.out.printf ("%tD", d);
                              // 1$ means use the first parameter
                              // t - time conversion, Date to String
                               // m - month as 2 digits with a 0
                               // d - day of month, as 2 digits with 0
                              // Y - 4 digit year
       System.out.printf (" - or: %1$tm/%1$td/%1$tY\n", d); 
   } // end for each date

 } // end main
 
 public static Date parseND (String s) {
   DateFormat dfm = DateFormat.getDateInstance(DateFormat.MEDIUM);
   DateFormat dfs = DateFormat.getDateInstance(DateFormat.SHORT);
   DateFormat dfy = new SimpleDateFormat ("y");

   try {return dfm.parse (s); } catch (ParseException e) {}
   try {return dfs.parse (s); } catch (ParseException e) {}
   try {return dfy.parse (s); } catch (ParseException e) {}
   return null;
 } // end parseND
 
} // end class DateExample


Date: Mar 17, 2017