How to decode a time value and add it to the current date (in Java)
The date/time classes of the standard Java library are rather
complex and not well documented.
The code snippet below demonstrates
how to parse a time string value and add the time value to a date value.
Download the complete test program: TestDateTime1.java
// Illustrates how to decode a time value and add it to todays date. public static void main (String args[]) throws Exception { int t = decodeTime("12:34:56"); Date today = getTodaysDate(); Date d = new Date(today.getTime()+t); System.out.println (d); } // Decodes a time value in "hh:mm:ss" format and returns it as milliseconds since midnight. public static synchronized int decodeTime (String s) throws Exception { SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss"); TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); f.setTimeZone (utcTimeZone); f.setLenient (false); ParsePosition p = new ParsePosition(0); Date d = f.parse(s,p); if (d == null || !isRestOfStringBlank(s,p.getIndex())) throw new Exception("Invalid time value (hh:mm:ss): \"" + s + "\"."); return (int)d.getTime(); } // Returns todays date without the time component. public static Date getTodaysDate() { return truncateDate(new Date()); } // Truncates the time component from a date/time value. // (The default time zone is used to determine the begin of the day). public static Date truncateDate (Date d) { GregorianCalendar gc1 = new GregorianCalendar(); gc1.clear(); gc1.setTime(d); int year = gc1.get(Calendar.YEAR), month = gc1.get(Calendar.MONTH), day = gc1.get(Calendar.DAY_OF_MONTH); GregorianCalendar gc2 = new GregorianCalendar(year,month,day); return gc2.getTime(); } // Returns true if string s is blank from position p to the end. public static boolean isRestOfStringBlank (String s, int p) { while (p < s.length() && Character.isWhitespace(s.charAt(p))) p++; return p >= s.length(); }
Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index