常见的日期问题计算
一:计算两个日期之间相差几天
- 1 /**
- 2 *
- 3 */
- 4 package com.hlcui.date;
- 5
- 6 import java.text.ParseException;
- 7 import java.text.SimpleDateFormat;
- 8 import java.util.Calendar;
- 9 import java.util.Date;
- 10
- 11 import org.junit.Test;
- 12
- 13 /**
- 14 * @author Administrator
- 15 *
- 16 */
- 17 public class DateTest {
- 18
- 19 @Test
- 20 public void testBetweenDays() throws ParseException {
- 21 int days = betweenDays("20160102", "20160303");
- 22 System.out.println(days);
- 23 }
- 24
- 25 /**
- 26 * 计算两个日期相差的天数
- 27 *
- 28 * @throws ParseException
- 29 */
- 30 public int betweenDays(String oldDate, String newDate)
- 31 throws ParseException {
- 32 Calendar cal = Calendar.getInstance();
- 33 cal.setTime(stringToDate(oldDate));
- 34 long oldTime = cal.getTimeInMillis();
- 35 cal.setTime(stringToDate(newDate));
- 36 long newTime = cal.getTimeInMillis();
- 37 return (int) ((newTime - oldTime) / (1000 * 24 * 3600));
- 38 }
- 39
- 40 /**
- 41 * String转换为Date
- 42 *
- 43 * @throws ParseException
- 44 */
- 45 public Date stringToDate(String date) throws ParseException {
- 46 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
- 47 return sdf.parse(date);
- 48 }
- 49
- 50 /**
- 51 * Date转换为String
- 52 */
- 53 public String dateToString(Date date) {
- 54 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
- 55 return sdf.format(date);
- 56 }
- 57 }
1:SimpleDateFormat类是一个格式化类,可以实现String类和Date之间的转换。
Format(Date):Date转为String类型,Parse(String):String类型转为Date类型。
2:Calendar.getInstance():可以通过Calendar的静态方法getInstance()获取Calendar对象。
3:Calendar.setTime(Date):设置日期 Calendar.getTime():获取1970年1月1日至今的毫秒数
二:计算当前日期距离本月最后一天的天数
days = (最后一天的毫秒数 — 当前天数的毫秒数)/ (1000*60*60*24)
- /**
- * 计算当天到月末还有几天
- */
- @Test
- public void calDays() {
- Date now = new Date();
- Calendar cal = Calendar.getInstance();
- // 设置最后一天时间
- cal.set(Calendar.DAY_OF_MONTH, cal.getMaximum(Calendar.DAY_OF_MONTH));
- long days = (cal.getTime().getTime() - now.getTime())
- / (1000 * 60 * 60 * 24);
- System.out.println(days);
- }
cal.set(Calendar.DAY_OF_MONTH, cal.getMaximum(Calendar.DAY_OF_MONTH));
其中Calendar类的API中
set(int field, int value)
将给定的日历字段设置为给定值。
其中day_of_month 与 date是同义词,用哪个都可以。
三:根据身份证号id计算年龄
- 1 @Test
- 2 public void testGetAgeById() {
- 3 String id = "320382199011044135";
- 4 System.out.println(getAgeById(id));
- 5 }
- 6
- 7 /**
- 8 * 根据身份证号id获取年龄age
- 9 *
- 10 * @throws ParseException
- 11 */
- 12 public String getAgeById(String id) {
- 13 if (DateTest.isNotEmpty(id)) {
- 14 String birthday = id.substring(6, 14);
- 15 birthday = birthday.substring(0, 4) + "-"
- 16 + birthday.substring(4, 6) + "-" + birthday.substring(6);
- 17 SimpleDateFormat sdf = new SimpleDateFormat(REGEX_SIMPLE);
- 18 try {
- 19 Date birthDate = sdf.parse(birthday);
- 20 int age = getAge(birthDate);
- 21 return String.valueOf(age);
- 22 } catch (ParseException e) {
- 23 e.printStackTrace();
- 24 }
- 25 }
- 26 return null;
- 27 }
- 28
- 29 /**
- 30 * 根据出生日期计算年龄
- 31 */
- 32 private int getAge(Date birth) {
- 33 // 计算当前时间(年、月、日)
- 34 Calendar cal = Calendar.getInstance();
- 35 int nowYear = cal.get(Calendar.YEAR);
- 36 int nowMonth = cal.get(Calendar.MONTH);
- 37 int nowDay = cal.get(Calendar.DAY_OF_MONTH);
- 38
- 39 // 计算出生时间(年、月、日)
- 40 cal.setTime(birth);
- 41 int birthYear = cal.get(Calendar.YEAR);
- 42 int birthMonth = cal.get(Calendar.MONTH);
- 43 int birthDay = cal.get(Calendar.DAY_OF_MONTH);
- 44
- 45 // age = nowYear - birthYear, 如果nowMonth<birthMonth age--
- 46 // 如果nowMonth == birthMonth 那么比较 nowDay < birthDay age--
- 47 int age = nowYear - birthYear;
- 48 if (nowMonth <= birthMonth) {
- 49 if (nowMonth == birthMonth) {
- 50 if (nowDay < birthDay) {
- 51 age--;
- 52 }
- 53 } else {
- 54 age--;
- 55 }
- 56 }
- 57 return age;
- 58
- 59 }
四:计算当前时间到月末小时数
- 1 @Test
- 2 public void testGetHours() {
- 3 System.out.println(getHours());
- 4 }
- 5
- 6 /**
- 7 * 计算当前时间距离月末的小时数
- 8 */
- 9 public long getHours() {
- 10 long hours = -1;
- 11 try {
- 12 // 当前时间毫秒数
- 13 Date currentDate = new Date();
- 14 long start = currentDate.getTime();
- 15
- 16 // 月末毫秒数
- 17 Calendar cal = Calendar.getInstance();
- 18 cal.set(Calendar.DAY_OF_MONTH, cal
- 19 .getActualMaximum(Calendar.DAY_OF_MONTH));
- 20 int year = cal.get(Calendar.YEAR);
- 21 int month = cal.get(Calendar.MONTH) + 1;
- 22 int day = cal.get(Calendar.DAY_OF_MONTH);
- 23 String endDate = year + "-" + month + "-" + day + " 24:00:00";
- 24 SimpleDateFormat sdf = new SimpleDateFormat(REGEX);
- 25 long end = sdf.parse(endDate).getTime();
- 26
- 27 // 小时数
- 28 hours = (end - start) / (1000 * 60 * 60);
- 29 } catch (ParseException e) {
- 30 e.printStackTrace();
- 31 }
- 32 return hours;
- 33 }
五:获取当前时间和前一天日期
- 1 // 获取当前时间和前一天日期
- 2 @Test
- 3 public void getCurrentTimeAndPreDate() {
- 4 SimpleDateFormat sdf = new SimpleDateFormat(REGEX);
- 5 System.out.println("当前时间为:\n" + sdf.format(new Date()));
- 6
- 7 Calendar cal = Calendar.getInstance();
- 8 cal.add(Calendar.DAY_OF_MONTH, -1);
- 9 System.out.println("前一天日期为:\n" + sdf.format(cal.getTime()));
- 10 }
六:获得指定日期的前一天,后一天
- 1 // 获得指定日期的前一天,后一天
- 2 @Test
- 3 public void getPreOrLastDayOfOneDay() {
- 4 try {
- 5 String date = "2012-10-09";
- 6 SimpleDateFormat sdf = new SimpleDateFormat(REGEX_SIMPLE);
- 7 Calendar cal = Calendar.getInstance();
- 8
- 9 cal.setTime(sdf.parse(date));
- 10 cal.add(Calendar.DAY_OF_MONTH, -1);
- 11 System.out.println("前一天的日期为:\n" + sdf.format(cal.getTime()));
- 12
- 13 cal.setTime(sdf.parse(date));
- 14 cal.add(Calendar.DAY_OF_MONTH, 1);
- 15 System.out.println("后一天的日期为:\n" + sdf.format(cal.getTime()));
- 16
- 17 } catch (Exception e) {
- 18 e.printStackTrace();
- 19 }
- 20
- 21 }
七:时间戳转日期格式
- 1 // 时间戳转日期格式
- 2 @Test
- 3 public void timestampConvertDate() {
- 4 long time = System.currentTimeMillis();
- 5 Date currentDate = new Date(time);
- 6 SimpleDateFormat sdf = new SimpleDateFormat(REGEX);
- 7 System.out.println("当前时间:\n" + sdf.format(currentDate));
- 8 }
八:计算某个日期是星期几
- 1 // 计算某个日期是星期几
- 2 @Test
- 3 public void calWeekdayByDate() {
- 4 try {
- 5 String date = "2016-11-06";
- 6 SimpleDateFormat sdf = new SimpleDateFormat(REGEX_SIMPLE);
- 7 Calendar cal = Calendar.getInstance();
- 8 cal.setTime(sdf.parse(date));
- 9
- 10 System.out.println("该天为星期"
- 11 + WEEKDAY[cal.get(Calendar.DAY_OF_WEEK)-1]);
- 12 } catch (Exception e) {
- 13 e.printStackTrace();
- 14 }
- 15
- 16 }
总结:
对于日期的操作在java编码中使用也是比较多的,主要有几个类Date类、Calendar类以及long类型、String类型
SimpleDateFormat转换类等,它们之间可以通过setTime()、getTime()等方法进行转换,如果需要获取某个日期,
可以通过add()、以及set()方法实现,应该掌握一些比较常用的常量类,例如:DAY_OF_MONTH、YEAR、MONTH、
DAY_OF_MONTH等等。