1 package org.apache.archiva.common.utils;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import java.util.Calendar;
23 import java.util.Date;
24 import java.util.GregorianCalendar;
27 * DateUtil - some (not-so) common date utility methods.
33 public static String getDuration( long duration )
35 return getDuration( new Date( 0 ), new Date( duration ) );
38 public static String getDuration( long ms1, long ms2 )
40 return getDuration( new Date( ms1 ), new Date( ms2 ) );
43 public static String getDuration( Date d1, Date d2 )
45 Calendar cal1 = new GregorianCalendar();
48 Calendar cal2 = new GregorianCalendar();
51 return getDuration( cal1, cal2 );
54 public static String getDuration( Calendar cal1, Calendar cal2 )
56 int year1 = cal1.get( Calendar.YEAR );
57 int day1 = cal1.get( Calendar.DAY_OF_YEAR );
58 int hour1 = cal1.get( Calendar.HOUR_OF_DAY );
59 int min1 = cal1.get( Calendar.MINUTE );
60 int sec1 = cal1.get( Calendar.SECOND );
61 int ms1 = cal1.get( Calendar.MILLISECOND );
63 int year2 = cal2.get( Calendar.YEAR );
64 int day2 = cal2.get( Calendar.DAY_OF_YEAR );
65 int hour2 = cal2.get( Calendar.HOUR_OF_DAY );
66 int min2 = cal2.get( Calendar.MINUTE );
67 int sec2 = cal2.get( Calendar.SECOND );
68 int ms2 = cal2.get( Calendar.MILLISECOND );
70 int leftDays = ( day1 - day2 ) + ( year1 - year2 ) * 365;
71 int leftHours = hour2 - hour1;
72 int leftMins = min2 - min1;
73 int leftSeconds = sec2 - sec1;
74 int leftMilliSeconds = ms2 - ms1;
76 if ( leftMilliSeconds < 0 )
78 leftMilliSeconds += 1000;
82 if ( leftSeconds < 0 )
100 StringBuffer interval = new StringBuffer();
102 appendInterval( interval, leftDays, "Day" );
103 appendInterval( interval, leftHours, "Hour" );
104 appendInterval( interval, leftMins, "Minute" );
105 appendInterval( interval, leftSeconds, "Second" );
106 appendInterval( interval, leftMilliSeconds, "Millisecond" );
108 return interval.toString();
111 private static void appendInterval( StringBuffer interval, int count, String type )
115 if ( interval.length() > 0 )
117 interval.append( " " );
120 interval.append( count );
121 interval.append( " " ).append( type );
124 interval.append( "s" );