Java8 时间操作总结

1. 获取当天日期

Java 8中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。

	public static void main(String[] args) {
	  LocalDate date = LocalDate.now();
	  System.out.println("当前日期=" + date);//2019-08-15
	}

2. 获取当前时间

时间精确到毫秒。

	public static void main(String[] args) {
	    LocalTime time = LocalTime.now();
	    System.out.println("当前时间=" + time);//18:11:17.878
	}

3. 获取当前日期和时间

返回当前时间的日期加时间:2019-08-15T18:11:17.877

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println(now);//2019-08-15T18:11:17.877
	}

4. 日期时间格式化

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println("now:" + now);
		System.out.println("now.format:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE));
		System.out.println("now.format:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
		System.out.println("now.format:" + now.format(DateTimeFormatter.ofPattern("Gyyyy MMM dd HH:mm:ss")));
		System.out.println("now.format:" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//		now:2019-08-15T18:46:21.159
//		now.format:2019-08-15
//		now.format:2019-08-15T18:46:21.159
//		now.format:公元2019 八月 15 18:46:21
//		now.format:2019-08-15 18:46:21
	}

5. 构造指定日期或者时间

调用工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开 始等等。

	public static void main(String[] args) {
	    LocalDate date1 = LocalDate.of(2000, 1, 1);
	    System.out.println("千禧年=" + date1);//千禧年=2000-01-01
		
	    LocalDateTime time = LocalDateTime.of(2019, 8, 15, 18, 28, 55);
	    System.out.println(time);//2019-08-15T18:28:55
	}

6. 获取年月日信息

这个就很神奇了,两条输出语句只能输出一条,注释掉后面的输出,前面的就可以正常输出了。

	public static void main(String[] args) {
	    LocalDate date = LocalDate.now();
	    System.out.println("99999");
	    System.out.printf("年=%d, 月=%d, 日=%d ", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
	    //年=2019, 月=8, 日=15
	    
	    LocalDateTime now = LocalDateTime.now();
	    System.out.printf("年=%d, 月=%d, 日=%d 时=%d 分=%d 秒=%d ", now.getYear(), now.getMonthValue(), now.getDayOfMonth(), now.getHour(), now.getMinute(), now.getSecond());
	    //年=2019, 月=8, 日=15 年=2019, 月=8, 日=15 时=18 分=34 秒=25 
	}

7. 日期时间计算

Java8提供了新的plusXxx()方法用于计算日期时间增量值,替代了原来的add()方法,使用minusXxx()代替了时间的减少,其中方法里面的参数值,如果写成负值,则效果会相反。新的API将返回一个全新的日期时间示例,需要使用新的对象进行接收。

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println(now);//2019-08-15T18:40:06.432
	    LocalDateTime minusDays = now.minusDays(3);
	    System.out.println(minusDays);//2019-08-12T18:40:06.432
	    LocalDateTime minusDays2 = now.minusDays(-3);
	    System.out.println(minusDays2);//2019-08-18T18:40:06.432
	    LocalDateTime plusDays = now.plusDays(3);
	    System.out.println(plusDays);//2019-08-18T18:40:06.432

     // 时间增量
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2);
        System.out.println("newTime=" + newTime);
        
     // 日期增量
        LocalDate date = LocalDate.now();
        LocalDate newDate = date.plus(1, ChronoUnit.WEEKS);
        System.out.println("newDate=" + newDate);
	}

8. 日期时间比较

    public static void main(String[] args) {
        
        LocalDate now = LocalDate.now();
        
        LocalDate date1 = LocalDate.of(2000, 1, 1);
        if (now.isAfter(date1)) {
            System.out.println("千禧年已经过去了");
        }
        
        LocalDate date2 = LocalDate.of(2020, 1, 1);
        if (now.isBefore(date2)) {
            System.out.println("2020年还未到来");
        }
        
    }

9. 日期 和 字符串的相互转换

    public static void main(String[] args) {
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        // 日期时间转字符串
        LocalDateTime now = LocalDateTime.now();
        String nowText = now.format(formatter);
        System.out.println("nowText=" + nowText);
        
        // 字符串转日期时间
        String datetimeText = "1999-12-31 23:59:59";
        LocalDateTime datetime = LocalDateTime.parse(datetimeText, formatter);
        System.out.println(datetime);
        
    }

10. Timestamp 和 LocalDateTime 互转

    public static void main(String[] args) {
    
        //Timestamp 转 LocalDateTime 
		Timestamp time = Timestamp.from(Instant.now());
		System.out.println(time);//		2019-08-15 19:06:26.09
		LocalDateTime localDateTime = time.toLocalDateTime();
		System.out.println(localDateTime);//		2019-08-15T19:06:26.090

		Instant now = Instant.now();
		System.out.println(now);//		2019-08-15T11:06:26.100Z

		//LocalDateTime  转 Timestamp
		Timestamp localDateTimeToTimestamp = Timestamp.valueOf(localDateTime);
		System.out.println(localDateTimeToTimestamp);//		2019-08-15 19:06:26.09
        
    }

11. Date 和 LocalDateTime 互转

    /**
     * Date转换为LocalDateTime
     * @param date
     */
    public static LocalDateTime date2LocalDateTime(Date date){
        Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
        ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }
 
    /**
     * LocalDateTime转换为Date
     * @param localDateTime
     */
    public static Date localDateTime2Date( LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault();
        //Combines this date-time with a time-zone to create a  ZonedDateTime.
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }
    
    public static void main(String[] args) {
    	LocalDateTime localDateTime = LocalDateTime.now();
		Date date = localDateTime2Date(localDateTime);
		System.out.println(date);//Sat Oct 12 09:55:21 CST 2019
		LocalDateTime date2LocalDateTime = date2LocalDateTime(date);
		System.out.println(date2LocalDateTime);//2019-10-12T09:55:21.278
	}

12 时间字符串转Timestamp


	public final static String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 时间字符串转Timestamp
     * @param dateStr
     * @param pattern 时间字符串格式:yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Timestamp dateStrToTimestamp(String dateStr, String pattern) {
    	if (StringUtils.isBlank(dateStr)) {
			return null;
		}
    	if (pattern.equals(DATE_PATTERN)) {
    		dateStr = dateStr + " 00:00:00";
    	}
    	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    	LocalDateTime datetime = LocalDateTime.parse(dateStr, formatter);
    	return Timestamp.valueOf(datetime);
    }

13 时间字符串格式转换 ( yyyy年MM月dd日 与 yyyy-MM-dd)


	/** 时间格式(yyyy年MM月dd日) */
	public final static String CHN_DATE_PATTERN = "yyyy年MM月dd日";
	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 时间格式转换
     * @param dateStr 原时间字符串
     * @param oldPattern 旧格式 yyyy年MM月dd日 or yyyy-MM-dd
     * @param newPattern 新格式  yyyy年MM月dd日 or yyyy-MM-dd
     * @return
     */
    public static String dateStrFormat(String dateStr, String oldPattern, String newPattern) {
    	if (StringUtils.isBlank(dateStr)) {
			return "";
		}
    	StringBuffer stringBuffer = new StringBuffer();
    	if (CHN_DATE_PATTERN.equals(oldPattern) && DATE_PATTERN.equals(newPattern)) {
    		if (dateStr.length() < 11) {
				return "";
			}
    		stringBuffer = new StringBuffer(dateStr.substring(0, 4)).append('-').append(dateStr.substring(5, 7)).append('-').append(dateStr.subSequence(8, 10));
    		return stringBuffer.toString();
		}else if (DATE_PATTERN.equals(oldPattern) && CHN_DATE_PATTERN.equals(newPattern)) {
			if (dateStr.indexOf("-") == -1) {
				return "";
			}
			String[] split = dateStr.split("-");
			if (split.length < 3) {
				return "";
			}
			stringBuffer = new StringBuffer(split[0]).append("年").append(split[1]).append("月").append(split[2]).append("日");
			return stringBuffer.toString();
		}
    	return "";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值