获取当前时间的几种方法整理(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哈哈

猜你喜欢

转载自www.cnblogs.com/ppppian2020/p/13166605.html