Merge branch 'v5-dev' of https://github.com/totalo/hutool into v5-dev

This commit is contained in:
tangguocheng1 2020-09-22 08:28:13 +08:00
commit f822b93326
4 changed files with 56 additions and 7 deletions

View File

@ -21,13 +21,7 @@ import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
@ -1389,6 +1383,30 @@ public class DateUtil extends CalendarUtil {
return new DateBetween(beginDate, endDate).betweenMonth(isReset);
}
/**
* 获取两个日期之间所有的月份
* @param start 开始时间
* @param end 结束时间
* @return List<String> 格式为yyyMM格式的月份列表 包含收尾</>
* @since 5.4.4
*/
public static List<String> getBetweenMonths(Date start, Date end) {
List<String> result = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
// 加一个月保证开始和结束同步时返回当月
tempStart.add(Calendar.MONTH, 1);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
result.add(sdf.format(start));
while (tempStart.before(tempEnd) || tempStart.equals(tempEnd)) {
result.add(sdf.format(tempStart.getTime()));
tempStart.add(Calendar.MONTH, 1);
}
return result;
}
/**
* 计算两个日期相差年数<br>
* 在非重置情况下如果起始日期的月小于结束日期的月年数要少算1不足1年

View File

@ -42,6 +42,7 @@ import java.util.TreeSet;
public class NetUtil {
public final static String LOCAL_IP = "127.0.0.1";
public static String LOCAL_HOSTNAME = "";
/**
* 默认最小端口1024
@ -533,6 +534,23 @@ public class NetUtil {
return null;
}
/**
* 获取主机名称
* @return 主机名称
* @since 5.4.4
*/
public static String getLocalHostName() {
try {
if (StrUtil.isNotBlank(LOCAL_HOSTNAME)) {
return LOCAL_HOSTNAME;
}
LOCAL_HOSTNAME = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LOCAL_HOSTNAME = getLocalhostStr();
}
return LOCAL_HOSTNAME;
}
/**
* 创建 {@link InetSocketAddress}
*

View File

@ -819,4 +819,12 @@ public class DateUtilTest {
final DateTime parse = DateUtil.parse(dt);
Assert.assertEquals("2020-06-03 12:32:12", parse.toString());
}
@Test
public void getBetweenMonthsTest() {
List<String> months1 = DateUtil.getBetweenMonths(new Date(), new Date());
Assert.assertEquals(1, months1.size());
List<String> months = DateUtil.getBetweenMonths(DateUtil.parse("2020-05-08 3:12:3"), new Date());
Assert.assertEquals(5, months.size());
}
}

View File

@ -74,4 +74,9 @@ public class NetUtilTest {
Assert.assertEquals("/", httpCookie.getPath());
Assert.assertEquals("cookiedomain.com", httpCookie.getDomain());
}
@Test
public void getLocalHostNameTest() {
System.out.println(NetUtil.getLocalHostName());
}
}