CalendarUtil

 1 package ch.makery.address.util;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Calendar;
 6 
 7 /**
 8  * Helper functions for handling dates.
 9  */
10 public class CalendarUtil {
11 
12   /**
13   * Default date format in the form 2013-03-18.
14   */
15   private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
16 
17   /**
18   * Returns the given date as a well formatted string. The above defined date
19   * format is used.
20   * 
21   * @param calendar date to be returned as a string
22   * @return formatted string
23   */
24   public static String format(Calendar calendar) {
25       if (calendar == null) {
26           return null;
27       }
28       return DATE_FORMAT.format(calendar.getTime());
29   }
30 
31   /**
32   * Converts a String in the format "yyyy-MM-dd" to a Calendar object.
33   * 
34   * Returns null if the String could not be converted.
35   * 
36   * @param dateString the date as String
37   * @return the calendar object or null if it could not be converted
38   */
39   public static Calendar parse(String dateString) {
40       Calendar result = Calendar.getInstance();
41       try {
42           result.setTime(DATE_FORMAT.parse(dateString));
43           return result;
44       } catch (ParseException e) {
45           return null;
46       }
47   }
48   
49   /**
50   * Checks the String whether it is a valid date.
51   * 
52   * @param dateString
53   * @return true if the String is a valid date
54   */
55   public static boolean validString(String dateString) {
56       try {
57           DATE_FORMAT.parse(dateString);
58           return true;
59       } catch (ParseException e) {
60           return false;
61       }
62   }
63 }
原文地址:https://www.cnblogs.com/cuizhf/p/3248429.html