View Javadoc

1   /*
2    *  File: TimeHelper.java 
3    *  Copyright (c) 2004-2007  Peter Kliem (Peter.Kliem@jaret.de)
4    *  A commercial license is available, see http://www.jaret.de.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of the Common Public License v1.0
8    * which accompanies this distribution, and is available at
9    * http://www.eclipse.org/legal/cpl-v10.html
10   */
11  package de.jaret.util.date;
12  
13  import java.text.ParseException;
14  import java.util.StringTokenizer;
15  
16  import de.jaret.util.misc.FormatHelper;
17  
18  /**
19   * Some methods helping to deal with time values.
20   * 
21   * @author Peter Kliem
22   * @version $Id: TimeHelper.java 242 2007-02-11 21:05:07Z olk $
23   */
24  public class TimeHelper {
25  
26      public static String secondsToString(int sec, boolean includeSeconds) {
27          int hours = sec / 3600;
28          int minutes = (sec % 3600) / 60;
29          int seconds = (sec % 60);
30          String str = FormatHelper.NFInt2Digits().format(hours) + ":" + FormatHelper.NFInt2Digits().format(minutes);
31          if (includeSeconds) {
32              str = str + ":" + FormatHelper.NFInt2Digits().format(seconds);
33          }
34          return str;
35      }
36  
37      public static int timeStringToSeconds(String str) throws ParseException {
38          try {
39              StringTokenizer tokenizer = new StringTokenizer(str, ":");
40              int h = Integer.parseInt(tokenizer.nextToken());
41              int m = Integer.parseInt(tokenizer.nextToken());
42              int s = 0;
43              if (tokenizer.hasMoreTokens()) {
44                  s = Integer.parseInt(tokenizer.nextToken());
45              }
46              return h * 3600 + m * 60 + s;
47          } catch (Exception e) {
48              throw new ParseException(str, 0);
49          }
50      }
51  
52  }