자바 - 시간

달 두 날짜 예제 코드 간의 차이를 달성하기 위해 계산

1. 메이븐 가져 오기 의존성 :

 <dependency>
	<groupId>joda-time</groupId>
		<artifactId>joda-time</artifactId>
	<version>2.9.6</version>
</dependency>

2. 연산 처리

package com.forezp.util;
import org.joda.time.DateTime;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* 在JAVA中,如何计算两个日期的月份差?<br>
*
*
* @author Administrator
*
*/
public class Demo1 {
	public static void main(String[] args) {
		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MMdd");
		DateTime start = formatter.parseDateTime("2017-07-11");
		DateTime end = formatter.parseDateTime("2017-11-19");
		int months = Months.monthsBetween(start, end).getMonths();
		System.out.println(months);
	}
}

자바 지정된 시간 동안 임의의 시간에 발생

 public static void main(String[] args) {
 
        for (int i=0;i<30;i++){
            Date date = randomDate("2019-01-01","2019-01-31");
            System.out.println(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date));
        }
    }
    private static Date randomDate(String beginDate,String endDate){
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(beginDate);
            Date end = format.parse(endDate);
 
            if(start.getTime() >= end.getTime()){
                return null;
            }
            long date = random(start.getTime(),end.getTime());
            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    private static long random(long begin,long end){
        long rtn = begin + (long)(Math.random() * (end - begin));
        if(rtn == begin || rtn == end){
            return random(begin,end);
        }
        return rtn;
    }
 

게시 18 개 원래 기사 · 원 찬양 16 ·은 20000 +를 볼

추천

출처blog.csdn.net/weixin_44569012/article/details/104082576