Java常用类:时间相关类

java.util.Datejava.util.Calendarjava.time
基本废弃,但有一个方法仍在使用目前程序中最常用的, 是抽象类Java 8 推出新的时间API

java.util.Date

getTime() 返回自1970.1.1以来的毫秒数

import java.util.Date;
public class DateTest {
	public static void main(String[] args) {
		Date d = new Date();
		System.out.println(d);
		System.out.println(d.getTime()); 
		//返回 1970.1.1 00:00:00 到现在的毫秒数
	}
}
输出:
Mon May 18 11:07:28 CST 2020
1589771248557

java.util.Calendar

Calendar c=Calendar.getInstance();
Calendar c= new GregorianCalendar();

以上两种方法都可调用

方法内容
get(Field)获取时间中每个属性的值. 注意, 月份0-11
getTime()返回相应的Date对象
getTimeInMillis()返回自1970.1.1以来的毫秒数
set(Field,amount)/set(year,month,day)设置时间字段,month的字段需+1输出
add(field, amount)根据指定字段增加/减少时间
roll(field, amount)根据指定字段增加/减少时间, 但不影响上一级的时间段
关于上述方法中(Field)的可用属性内容
Calendar.YEAR获取年
Calendar.MONTH获取月,这里月份的范围为0~11,因此获取月份的时候需要+1才是当前月份值,例:get(Calendar.MONTH) + 1
Calendar.DAY_OF_MONTH/Calendar.DATE获取日
Calendar.HOUR获取时
Calendar.HOUR_OF_DAY获取时,24小时值
Calendar.MINUTE获取分
Calendar.SECOND获取秒
Calendar.DAY_OF_WEEK获取西方国家的星期,西方国家星期从星期日开始计算,需要-1才是中国星期,例:get(Calendar.DAY_OF_WEEK)-1

具体操作见下:

import java.util.Calendar;
public class CalendarTest {	
	Calendar calendar = Calendar.getInstance();	
	//test1方法,获取当前时间
	public void test1() {
        int year = calendar.get(Calendar.YEAR); // 获取年       
        int month = calendar.get(Calendar.MONTH) + 1; // 获取月,这里月份的范围为0~11,因此获取月份的时候需要+1才是当前月份值     
        int day = calendar.get(Calendar.DAY_OF_MONTH);   // 获取日       
        int hour = calendar.get(Calendar.HOUR); // 获取时
        // int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时表示      
        int minute = calendar.get(Calendar.MINUTE);  // 获取分       
        int second = calendar.get(Calendar.SECOND); // 获取秒       
        int weekday = calendar.get(Calendar.DAY_OF_WEEK)-1; // 星期,英语国家星期从星期日开始计算
        System.out.println("现在是" + year + "年" + month + "月" + day + "日" + hour
                + "时" + minute + "分" + second + "秒" + "星期" + weekday);
    }

    // test2方法,获取一年后的今天
    public void test2() {
        // 同理换成下个月的今天calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.YEAR, 1); 
        int year = calendar.get(Calendar.YEAR);  // 获取年        
        int month = calendar.get(Calendar.MONTH) + 1;// 获取月       
        int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取日
        System.out.println("一年后的今天:" + year + "年" + month + "月" + day + "日");
    }

    //test3方法,获取任意一个月的最后一天(此方法无需判断闰年等,直接通过两个方法解决)
    public void test3() {
        // 假设求6月的最后一天
        int currentMonth = 6;
        // 先求出7月份的第一天,实际中这里6为外部传递进来的currentMonth变量
        calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);//设置时间字段,年,月,日
        calendar.add(Calendar.DATE, -1);//将当前时间减少一天即为上个月最后一天的时间
        int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取(修改后)时间
        System.out.println("6月份的最后一天为" + day + "号");
    }

    // test4方法,设置日期
    public void test4() {
        calendar.set(Calendar.YEAR, 2000);//设置年份为2000年
        System.out.println("现在是" + calendar.get(Calendar.YEAR) + "年");

        calendar.set(2018, 7, 8);//月份是需要+1呈现       
        int year = calendar.get(Calendar.YEAR); // 获取年      
        int month = calendar.get(Calendar.MONTH)+1;  // 获取月    
        int day = calendar.get(Calendar.DAY_OF_MONTH);// 获取日

        System.out.println("现在是" + year + "年" + month + "月" + day + "日");
    }
    
    //test5,add和roll的区别
    public void test5() {     
        calendar.set(2018, 7, 8);//将时间设为2018年7月8日
        calendar.add(Calendar.DAY_OF_MONTH, -8);//人性化加减时间        
        int year = calendar.get(Calendar.YEAR);// 获取年       
        int month = calendar.get(Calendar.MONTH)+1; // 获取月        
        int day = calendar.get(Calendar.DAY_OF_MONTH);// 获取日
        System.out.println("2018.8.8, 用add减少8天,现在是" + year + "." + month + "." + day);
        
        calendar.set(2018, 7, 8);//将时间设为2018年7月8日
        calendar.roll(Calendar.DAY_OF_MONTH, -8);//只加减日这一项,不影响其他年月                
        year = calendar.get(Calendar.YEAR);// 获取年        
        month = calendar.get(Calendar.MONTH)+1;// 获取月        
        day = calendar.get(Calendar.DAY_OF_MONTH);// 获取日
        System.out.println("2018.8.8, 用roll减少8天,现在是" + year + "." + month + "." + day);
    }
        
	public static void main(String[] args) {//main函数
		CalendarTest c = new CalendarTest();
		c.test1();
		System.out.println("============");
		c.test2();
		System.out.println("============");
		c.test3();
		System.out.println("============");
		c.test4();
		System.out.println("============");
		c.test5();
	}
}
输出:
现在是202051815513秒星期1
============
一年后的今天:2021518============
6月份的最后一天为30============
现在是2000年
现在是201888============
2018.8.8, 用add减少8天,现在是2018.7.31
2018.8.8, 用roll减少8天,现在是2018.8.31

java.time包

java.time包中的类内容
LocalDate日期类
LocalTime时间类(时分秒-纳秒)
LocalDateTimeLocalDate + LocalTime
Instant时间戳

java.time.LocalDate:
LocalDate today = LocalDate.now();

方法内容
getYear()获取年
getMonthValue()获取月
getDayOfYear()/getDayOfMonth()获取这一天是这年/月的第几天
getDayOfWeek()获取这天是这周的星期几
isLeapYear()判断是否闰年
isBefore(LocalDate.of(year,month,day))/isAfter(LocalDate.of(year,month,day))判断当前时间时候在()内的时间之前或之后
atTime(LocalTime.now())获取当前时间
plusYears()/plusMonths()/plusDays()/plusWeeks()当前时间加年/月/日/周
minusYears()/minusMonths()/minusDays()/minusWeeks()当前时间减年/月/日/周
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;
 
public class DateUtil { 
    public static void main(String[] args) { 
        LocalDate today = LocalDate.now();
        //判断是否是闰年
        System.out.println("今年"+today.get()+"是闰年?"+today.isLeapYear());
 
        //今天和01/01/2015比较
        System.out.println("今天处于2015年1月1日之前吗? "+today.isBefore(LocalDate.of(2015,1,1)));
 
        //当前时间
        System.out.println("当前时间="+today.atTime(LocalTime.now()));
 
        //加减时间
        System.out.println("10天后:"+today.plusDays(10));
        System.out.println("3周后:"+today.plusWeeks(3));
        System.out.println("20个月后:"+today.plusMonths(20));
 
        System.out.println("10天前:"+today.minusDays(10));
        System.out.println("3周前:"+today.minusWeeks(3));
        System.out.println("20个月前:"+today.minusMonths(20));
 
        //调整时间
        System.out.println("First date of this month= "+today.with(TemporalAdjusters.firstDayOfMonth()));
        LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("Last date of this year= "+lastDayOfYear);
 
        //时间段计算
        Period period = today.until(lastDayOfYear);
        System.out.println("Period Format= "+period);
        System.out.println("Months remaining in the year= "+period.getMonths());        
    }
}
输出:
今年2020是闰年?true
今天处于201511日之前吗? false
当前时间=2020-05-18T14:37:43.224619700
10天后:2020-05-28
3周后:2020-06-08
20个月后:2022-01-18
10天前:2020-05-08
3周前:2020-04-27
20个月前:2018-09-18
First date of this month= 2020-05-01
Last date of this year= 2020-12-31
Period Format= P7M13D
Months remaining in the year= 7

java.time.LocalTime
LocalTime time = LocalTime.now();


import java.time.LocalTime;
import java.time.ZoneId;

public class LocalTimeExample { 
    public static void main(String[] args) { 
        //当前时间  时分秒 纳秒
        LocalTime time = LocalTime.now();
        System.out.println("当前时间:"+time);
 
        //根据时分秒
        LocalTime specificTime = LocalTime.of(12,20,25,40);
        System.out.println("Specific Time of Day="+specificTime);
 
        //错误的时间参数 将报DateTimeException
        //LocalTime invalidTime = LocalTime.of(25,20);
 
        //上海时间
        LocalTime timeSH = LocalTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println("上海时间:"+timeSH);
         
        //一天当中第几秒
        LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
        System.out.println("10000th second time= "+specificSecondTime); 
    } 
}
输出:
当前时间:14:56:40.294609300
Specific Time of Day=12:20:25.000000040
上海时间:14:56:40.296612400
10000th second time= 02:46:40

java.time.LocalDateTime
LocalDateTime today = LocalDateTime.now();


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
 
public class LocalDateTimeExample { 
    public static void main(String[] args) {
        //当前日期 时分秒
        LocalDateTime today = LocalDateTime.now();
        System.out.println("当前日期:"+today);
 
        //根据日期, 时分秒来创建对象
        today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
        System.out.println("Current DateTime="+today);
 
        //指定具体时间来创建对象
        LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
        System.out.println("Specific Date="+specificDate);
 
        //如时间不对,将报异常DateTimeException
        //LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1);
        
        //上海时区
        LocalDateTime todayShanghai = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println("上海时间:"+todayShanghai);
          
        //从01/01/1970 10000秒
        LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
        System.out.println("10000th second time from 01/01/1970= "+dateFromBase); 
    } 
}
输出:
当前日期:2020-05-18T14:59:02.747737600
Current DateTime=2020-05-18T14:59:02.748862200
Specific Date=2014-01-01T10:10:30
上海时间:2020-05-18T14:59:02.750756800
10000th second time from 01/01/1970= 1970-01-01T02:46:40

java.time.Instant
Instant timestamp = Instant.now();

import java.time.Instant;
import java.util.Date;
 
public class InstantExample { 
    public static void main(String[] args) {
        //当前时间戳
        Instant timestamp = Instant.now();
        System.out.println("Current Timestamp = "+timestamp);
 
        //从毫秒数来创建时间戳
        Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
        System.out.println("Specific Time = "+specificTime);
 
        Date date = Date.from(timestamp); 
        System.out.println("current date = " + date);
    } 
}
输出:
Current Timestamp = 2020-05-18T07:00:33.743040100Z
Specific Time = 2020-05-18T07:00:33.743Z
current date = Mon May 18 15:00:33 CST 2020
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐