001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.util; 018 019 import java.util.Date; 020 import java.util.Locale; 021 import java.util.concurrent.TimeUnit; 022 023 /** 024 * A helper class for working with times in various units 025 * 026 * @version 027 */ 028 public class Time { 029 private long number; 030 private TimeUnit timeUnit = TimeUnit.MILLISECONDS; 031 032 public Time(long number, TimeUnit timeUnit) { 033 this.number = number; 034 this.timeUnit = timeUnit; 035 } 036 037 public static Time millis(long value) { 038 return new Time(value, TimeUnit.MILLISECONDS); 039 } 040 041 public static Time seconds(long value) { 042 return new Time(value, TimeUnit.SECONDS); 043 } 044 045 public static Time minutes(long value) { 046 return new Time(minutesAsSeconds(value), TimeUnit.MILLISECONDS); 047 } 048 049 public static Time hours(long value) { 050 return new Time(hoursAsSeconds(value), TimeUnit.MILLISECONDS); 051 } 052 053 public static Time days(long value) { 054 return new Time(daysAsSeconds(value), TimeUnit.MILLISECONDS); 055 } 056 057 public long toMillis() { 058 return timeUnit.toMillis(number); 059 } 060 061 public Date toDate() { 062 return new Date(toMillis()); 063 } 064 065 public long getNumber() { 066 return number; 067 } 068 069 public TimeUnit getTimeUnit() { 070 return timeUnit; 071 } 072 073 protected static long minutesAsSeconds(long value) { 074 return value * 60; 075 } 076 077 protected static long hoursAsSeconds(long value) { 078 return minutesAsSeconds(value) * 60; 079 } 080 081 protected static long daysAsSeconds(long value) { 082 return hoursAsSeconds(value) * 24; 083 } 084 085 @Override 086 public String toString() { 087 return number + " " + timeUnit.toString().toLowerCase(Locale.ENGLISH); 088 } 089 }