zoukankan      html  css  js  c++  java
  • 日期

    Calendar

     

    DAY_OF_YEAR

    Field number for get and set indicating the day number within the current year.  The first day of the year has value 1.

    每个月的第一天用1表示

     

    MONTH

    Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year

    月份的第一个用0表示,即一月份是用0表示

    下面有两种方式计算两个日期之间的天数只差

    package com.robert.Date;
    
    import java.util.Calendar;
    
    public class DateUtils {
    
    	public static void main(String[] args) {
    		Calendar calendar1 = Calendar.getInstance();
    		calendar1.set(2013, 9, 8);
    		Calendar calendar2 = Calendar.getInstance();
    		calendar2.set(2010, 8, 16);
    		System.out.println(getDays(calendar1, calendar2));
    		System.out.println(getDays2(calendar1,calendar2));
    	}
    
    	/**
    	 * 取得两个日期之间得天数
    	 * @param date1	 前面的日期
    	 * @param date2	 后面的日期
    	 * @return
    	 */
    	public static int getDays(Calendar date1, Calendar date2) {
    		int y1 = date1.get(Calendar.YEAR);
    		int y2 = date2.get(Calendar.YEAR);
    		int d1 = date1.get(Calendar.DAY_OF_YEAR);
    		int d2 = date2.get(Calendar.DAY_OF_YEAR);
    		return (y1-y2)*365+(d1 - d2);
    	}
    	
    	/**
    	 * 通过获取毫秒来计算天数之差
    	 * @param date1
    	 * @param date2
    	 * @return
    	 */
    	public static long getDays2(Calendar date1,Calendar date2){
    		long time1 = date1.getTimeInMillis();
    		long time2 = date2.getTimeInMillis();
    		long diff = time1 - time2;
    		long days = diff/(24*60*60*1000);
    		return days;
    	}
    }
    

    方式一的输出结果为:1117

    方式二的输出结果为:1118

    发现第一种方式错误!

    有的年份是瑞年,所以出现了不同的结果,上述给出的日期区间内2012年为闰年。


     

  • 相关阅读:
    机器学习实战1:朴素贝叶斯模型:文本分类+垃圾邮件分类
    Hadoop实战1:MapR在ubuntu集群中的安装
    建站、开发工具,持续更新。。。
    Mysql多表联合更新、删除
    List的深度copy和浅度拷贝
    HashMap和List遍历方法总结及如何遍历删除元素
    for循环的两种写法哪个快
    MySQL的隐式类型转换整理总结
    Java BigDecimal类的使用和注意事项
    MySQL DECIMAL数据类型
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986806.html
Copyright © 2011-2022 走看看