java日期时间类型的相关操作

1、Date 日期时间类型

  1. 毫秒值的作用:可以对时间和日期进行计算,可以日期转换为毫秒进行计算,计算完毕,在把毫秒转换为日期:(1000毫秒 == 1秒)
  2. 把毫秒转换为日期:1天=24x 60 x 60 = 86400秒=86400 x 1000 = 86400000毫秒

Date 常用方法

1)	new  Date()          	// 获取当前系统的日期和时间
2)	new Date(long date)  	// 传递毫秒值,把毫秒值转换为Date日期
3)	Long getTime() // 把日期转换为毫秒值(相当于System. current TimeMillis()方法),返回自1970年1月1日00:00:00 GMT以来此Date对象表示的毫秒数。
4)	after(Date when)        // 测试此日期是否在指定日期之后。
5)	before(Date when)       //   测试此日期是否在指定日期之前。
6)	setTime(long time) 
          		// 设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
7)	toString() 
//把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。

year 1900 的年份至今。
month 0-11 之间的月份。
date 一月中 1-31 之间的某一天。
hrs 0-23 之间的小时数。
min 0-59 之间的分钟数。
sec 0-59 之间的秒数。

2、DateFormat日期格式化抽象类

作用:格式化 (也就是日期-> string、解析(string->日期)

日期格式模式: yyyy年M月dd日 EEEE(星期) H时mm分ss秒

DateFormat常用方法

  1. String format(Date date) : 将Date日期,格式化为符合模式的字符串
  2. Date parse(String source): 将字符串,解析为Date日期

SimpleDateFormat常用方法:是DateFormat子类
3. SimpleDateFormat(String pattern) SimpleDateFormat 构造pattern :传递指定的模式,
y 年 M 月 d 日 EEEE (星期) H 时 m 分 s 秒

//1.创建s impLeDateFormat对象构造方法中传 递指定的模式
SimpleDateFormat sdf = new SimpleDateFormat( pattrn: "yyyy年M月dd日   EEEE HH时mm分ss秒");
//2.调用SimpleDateFormat对象中的方法format ,按照构造方法中指定的模式,把Date日期格式化为符合模式的字符串(文本)
//String format(Date date)按照指定的模式, 把Date日期,格式化为符合模式的字符串
Date date = new Date();
String d = sdf.format(date);			将日期转换为string类型
System.out.println(date);//Sun Aug 08 15:51:54 CST 2088
System.out.println(d);	//2088年08月08日 星期五 15时51分54秒

3、日期工具类

// 1、获取Calendar实例
		Calendar cal= Calendar.getInstance();
		
// 2、初始值
// 代码如下,值得指出的是由于我们的时区设置是GMT+8,所以打印格林威治时间得到的是1970-01-01 08:00:00.
Calendar cal = Calendar.getInstance();//得到当前时间
cal.setTimeInMillis(0);//转换成格林威治时间

// 3、获取值
cal.get(Calendar.YEAR);//年
cal.get(Calendar.MONTH) + 1;//月(必须要+1)
cal.get(Calendar.DATE);//日
cal.get(Calendar.HOUR_OF_DAY);//时
cal.get(Calendar.MINUTE);//分
cal.get(Calendar.SECOND);//秒
cal.get(Calendar.DAY_OF_WEEK);//星期(Locale.ENGLISH情况下,周日是1,剩下自己推算)
//注意:如果拿时间不是为了计算而是展示出来,肯定用SimpleDateFormart了,模式为yyyy-MM-dd HH:mm:ss

// 4、设置值
cal.set(2013, 5, 4, 13, 44, 51);	//年月日时分秒(月份0代表1月)
cal.set(Calendar.YEAR, 2014);		//年
cal.set(Calendar.MONTH, 7);		//月(月份0代表1月)
cal.set(Calendar.DATE, 11);		//日
cal.set(Calendar.HOUR_OF_DAY, 15);//时
cal.set(Calendar.MINUTE, 33);		//分
cal.set(Calendar.SECOND, 32);		//秒
cal.getTimeInMillis()				// 获取Calendar对象的毫秒值

// 5、运算值
cal.add(Calendar.YEAR, 1);	//年
cal.add(Calendar.MONTH, 1);	//月
cal.add(Calendar.DATE, 1);	//日
cal.add(Calendar.HOUR_OF_DAY, -1);//时
cal.add(Calendar.MINUTE, 1);	//分
cal.add(Calendar.SECOND, 1);	//秒
cal.add(Calendar.DATE, 7);	//周

4、Date类型之间的比较

@Test
public void test02(){
	// 获取第一个日期类型对象
    Date date1 = new Date();
	// 获取日期工具对象,并获取系统时间
    Calendar calendar = Calendar.getInstance();
    // 指定年份为2019年
    calendar.set(Calendar.YEAR,2019);
    // 从工具类中获取Date对象
    Date date2 = calendar.getTime();
    // 指定容器格式化的格式
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd EEEE HH:mm:ss");
    String format1 = format.format(date1);
    String format2 = format.format(date2);
    /* format1.compareTo(format2) = 1  表示date1时间大于date2
    *  format1.compareTo(format2) = 0  表示两个时间一致
    *  format1.compareTo(format2) = -1 表示date1小于date2
    * */
    System.out.println(format2.compareTo(format1));
}

5、SpringBoot关于日期的配置

application.properties文件配置 默认是按yyyy/MM/dd格式

spring.mvc.format.date=yyyy-MM-dd

6、计算两个date对象差值,并输出相差的天数

java

public static int getDayDiffer(Date startDate, Date endDate) throws ParseException {
		// 指定日期格式化类型
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    // 按指定类型获取容器的毫秒值
	    long startDateTime = dateFormat.parse(dateFormat.format(startDate)).getTime();
	    long endDateTime = dateFormat.parse(dateFormat.format(endDate)).getTime();
	    // 将两个日期进行相减,并除以一天的毫秒值,即可得到,相差的天数
	    return (int) ((endDateTime - startDateTime) / (1000 * 3600 * 24));
}

JS

//JS获取两个日期之间相差的天数
function  getDaysBetween(dateString1,dateString2){
   var  startDate = Date.parse(dateString1);
   var  endDate = Date.parse(dateString2);
   var days=(endDate - startDate)/(1*24*60*60*1000);
   // alert(days);
   return  days;
}

5、JS格式化日期

Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}

// 比如我们可以这样调用下:
var time1 = new Date().format("yyyy-MM-dd hh:mm:ss");
console.log(time1);

输出的结果

hutool天 转 毫秒 java 毫秒转换成日期 java_javascript

// 2. 将指定的日期转换为"年月日"的格式,代码如下:
    var oldTime = (new Date("2012/12/25 20:11:11")).getTime();
    var curTime = new Date(oldTime).format("yyyy-MM-dd");
    console.log(curTime);
   运行如下:
   
// 3. 将 "时间戳" 转换为 "年月日" 的格式.
  比如如下代码: 
    var da = 1402233166999;
    da = new Date(da);
    var year = da.getFullYear()+'年';
    var month = da.getMonth()+1+'月';
    var date = da.getDate()+'日';
    console.log([year,month,date].join('-'));

运行如下

hutool天 转 毫秒 java 毫秒转换成日期 java_日期转换_02

8、Json返回格式化日期类型

导入依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.2</version>
</dependency>

在实体类日期类型上加上@JsonFormat注解

public class Student {
    private int id;
    private String username;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createDate;
    //getter setter省略。。。
}

注意:引入fasterxml maven jar包之后,就可以在实体类日期类型属性上面使用@JsonFormat注解了,要注意的是,它只会在类似@ResponseBody返回json数据的时候,才会返回格式化的yyyy-MM-dd HH:mm:ss时间,你直接使用System.out.println()输出的话,仍然是类似“Fri Dec 01 21:05:20 CST 2017”这样的时间样式。