Java tutorial
package de.fhg.iais.commons.time; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /****************************************************************************** * Copyright 2011 (c) Fraunhofer IAIS Netmedia http://www.iais.fraunhofer.de * * ************************************************************************** * * 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 org.apache.commons.lang.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class StopWatch { private static final Logger LOG = LoggerFactory.getLogger(StopWatch.class); private long start; private long daysMilliseconds = 86400000; private StopWatch() { } public static synchronized StopWatch start() { StopWatch st = new StopWatch(); st.start = System.currentTimeMillis(); return st; } public long stop() { long diff = System.currentTimeMillis() - this.start; return diff; } public void stop(String explain) { LOG.info(explain + " " + stopTime()); } public String stopTime() { return DateFormatUtils.formatUTC(stop(), DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern()); } public String stopTimeFormat(String format, TimeZone zone) { if (format == null || format.equals("")) { format = "'P'DDD'DT'HH'H'mm'M'ss'S'"; } if (zone == null) { zone = TimeZone.getTimeZone("GMT0"); } long end = stop(); if (end < this.daysMilliseconds) { Date endDate = new Date(end); SimpleDateFormat formatter = new SimpleDateFormat("'000D:'HH'h:'mm'm:'ss's'"); formatter.setTimeZone(zone); return formatter.format(endDate); } else { end -= this.daysMilliseconds; Date endDate = new Date(end); SimpleDateFormat formatter = new SimpleDateFormat(format); formatter.setTimeZone(zone); return formatter.format(endDate); } } }