实现构造一个时间,获取当前时间戳,日期时间与时间戳的互换等操作
import java.text.SimpleDateFormat; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.Date; // Java时间操作的一些实例 By Titan 2020-04-01 public class TimeStudy { public static void main(String[] args) { formatDate(); dateCovert(); } // 格式化当前时间 public static void formatDate() { System.out.println("Format Date"); // 老API方式 Date date = new Date(); String strDateFormat = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); System.out.println("The formatted date is : "); System.out.println(sdf.format(date)); // Java8方式 LocalDateTime lt = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("The formatted date is : "); System.out.println(formatter.format(lt)); System.out.println("-------------------------------------------------------"); } // 时间戳与时间日期的互相转换 public static void dateCovert() { LocalDateTime lt = LocalDateTime.now(); // 获取当前时间戳 // 秒级时间戳 long timestamp = lt.toEpochSecond(ZoneOffset.ofHours(8)); // 毫秒级时间戳 long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli(); System.out.println("The current timestamp is: \n" + timestamp); System.out.println("The current millisecond timestamp is: \n" + milliSecond); // 获取任意时间的时间戳 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime newLt = LocalDateTime.parse("2019-01-01 00:00:00", formatter); long millSecond2 = newLt.toInstant(ZoneOffset.ofHours(8)).toEpochMilli(); System.out.println("The mill-second of 2019-01-01 00:00:00 is:\n" + millSecond2); // 时间戳转时间 Instant ins = Instant.ofEpochMilli(millSecond2); LocalDateTime localDateTime = LocalDateTime.ofInstant(ins, ZoneOffset.ofHours(8)); String dateTimeText = localDateTime.format(formatter); System.out.println("The LocalDateTime of " + millSecond2 + " is:\n" + dateTimeText); System.out.println("-------------------------------------------------------"); } }
结果类似于下面
JDK8中的新特性:用 LocalDateTime 与 DateTimeFormatter 代替了老的 Date 与 SimpeDateFormat,更加的方便,进行时间日期的运算也更加简洁了。
文章评论