java時間的一些處理

時間的一些處理

獲取當前的時間:

時間戳:
System.currentTimeMillis() //第一種
Date date = new Date();
System.out.println(date.getTime()); //第二種

格式化時間

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss"); //可以自定義一個格式
String dataString = sdf.format(new date());

反向解析時間

String timeString="2019-11-16_15_03_14";
Date date3 =new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").parse(timeString);
System.out.println(date3);

時間相關的計算

long time2=System.currentTimeMillis();
Date date2 =new Date(time2-1000);
System.out.println(sdf.format(date2));

Calendar時間

方便計算時間使用

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.MONTH)+1);//獲取當前的月份,月份需要加1
System.out.println("------2小時之前時間---------");
now.add(Calendar.HOUR_OF_DAY, -2);
System.out.println(sdf.format(now.getTime()))
Calendar now = Calendar.getInstance();
System.out.println("年:" + now.get(Calendar.YEAR));
System.out.println("月:" + (now.get(Calendar.MONTH) + 1));
System.out.println("日:" + now.get(Calendar.DAY_OF_MONTH));
System.out.println("時:" + now.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + now.get(Calendar.MINUTE));
System.out.println("秒:" + now.get(Calendar.SECOND));

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章