獲取當前時間的幾種方法整理(Java)


在java中有很多方法可以取到系統時間,記一下最簡單的那種

//使用Calendar 獲取當前日期和時間
Calendar calendar = Calendar.getInstance(); // get current instance of the calendar 
//轉換格式  使用format將這個日期轉換成我們需要的格式
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");  
System.out.println(formatter.format(calendar.getTime()));

下面整理一下其他集中方法(省略導包)

一、使用java.util.Date類

這是一種直接實例化位於Java包java.util的Date類的方法

//添加當前時間
Date now = new Date(); 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式(年-月-日-時-分-秒)
String createTime = dateFormat.format(now);//格式化然后放入字符串中

/*
*DateFormat 是日期/時間格式化子類的抽象類,因為他是一個抽象類,所以要有具體構造方法 
*public class SimpleDateFormatextends DateFormatSimpleDateFormat
* 是一個以與語言環境有關的方式來格式化和解析日期的具體類

*public final String format(Date date)將一個 Date 格式化為日期/時間字符串。
*SimpleDateFormat() 用默認的模式顯示時間
*SimpleDateFormat(String pattern) 用給定的模式顯示時間
 

二、利用System.currentTimeMillis() (此方法不受時區的影響,但會根據系統的時間返回當前值,世界各地的時區是不一樣的)

這個方法得到的結果是時間戳的格式,類似 1543105352845 這樣

容易出現bug

//將時間戳轉換成時間格式
long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒");
Date date = new Date(currentTime);
System.out.println(formatter.format(date));

三、使用Calendar API(常用)

//使用Calendar 獲取當前日期和時間
Calendar calendar = Calendar.getInstance(); // get current instance of the calendar 
//轉換格式  使用format將這個日期轉換成我們需要的格式
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");  
System.out.println(formatter.format(calendar.getTime()));

四、使用Date/Time API (常用)

Java 8過后 提供了一個全新的API 來替代(java.util.Date和java.util.Calendar)

該API包括了類:

  • LocalDate
  • LocalTime
  • LocalDateTime
  • ZonedDateTime

a)、LocalDate

LocalDate用來獲取一個日期,並不能得到具體時間

實例:

LocalDate date = LocalDate.now(); // get the current date 
//格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");  
System.out.println(date.format(formatter)); 

結果:

18-06-2020

b)、LocalTime

LocalTime和LocalDate相反,只代表一個時間,無法獲取日期

實例:

LocalTime time = LocalTime.now(); // get the current time  
//格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");  
System.out.println(time.format(formatter)); 

結果:

18:00:58 

c)、LocalDateTime

LocalDateTime,也是Java中最常用的Date / Time類,代表前兩個類的組合 - 即日期和時間的值

實例:

LocalDateTime dateTime = LocalDateTime.now(); // get the current date and time  
//格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");  
System.out.println(dateTime.format(formatter));  

結果:

18-06-2020 18:02:38 

d)、ZonedDateTime

ZonedDateTime是帶時區的時間和日期

不做具體整理了


這段時間一直在忙畢業的材料,終於畢業啦,從此就是一個卑微社畜啦。下半年也要好好加油,爭取完成小本本上的Task哈哈


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM