Comprehensive analysis of Java API Date Time

Time zone

  • GMT (Greenwich Mean Time): Greenwich Mean Time, GMT noon is when the sun crosses the Greenwich meridian (that is, at the highest point over Greenwich) time.
  • UTC (Universal Time Coordinated): harmonization of time, which is based on atomic seconds long, as close as possible in the GMT time, UTC time standard yyyy-MM-dd'T'HH:mm:ss.SSSXXX.

GMT is no longer used as a standard time, UTC is the most important in the world time standard.

Java provides a method to get the current time

  • System.currentTimeMillis (), returns the current time, in milliseconds, to the current moment is represented 1970-01-01 00:00:00.000in milliseconds difference. The return value can be used to initialize long java.util.Date, java.sql.Date, java.sql.Timestamp java.util.GregorianCalendar and objects.
  • To System.nanoTime (), return a time value (the current value of the system timer), the nearest nanosecond. It is a time provided by the JVM, primarily used to accurately measure the time between two time periods

For example, some of the code needs to be performed to measure how long to achieve the following,

long startTime = System.nanoTime();
//...the code being measured
long estimatedTime = System.nanoTime() - startTime;

Time granularity
fact, time granularity System.currentTimeMillis () method is greater than 1 millisecond. If you repeatedly perform this method, you will find that the result will be the same a short time, and then suddenly at a time results in an increase of tens of milliseconds (may be more). This is normal, after all, this method is certainly not the world's most sophisticated timer.

Old Time API

There are many problems of old time API, for example,

  • Java defined date / time is not the same class, and in java.util package java.sql class includes the date, in addition to formatting and parsing the class definition java.text package.
  • java.util.Date contains the date and time, and contains only java.sql.Date date will be incorporated into the package java.sql unreasonable. In addition these two classes have the same name, which itself is a very bad design.
  • For the time, timestamp, formatting and parsing, and some classes have not clearly defined. Demand for formatting and parsing, we have java.text.DateFormat abstract class, but usually, SimpleDateFormat class is used for such needs.
  • All dates are variable class, so they are not thread-safe, which is one of the biggest problems date Java classes.
  • Date class does not offer international, no time zone support, so the introduction of Java and java.util.TimeZone java.util.Calendar class, but they are all above problems also exist.

java.util.Date class

java.util.Date class encapsulates the date and time information, it is generally only display a date, he does not make any operation processing, Calendar class recommended for treatment, convenience of calculation. The following obsolete method is not listed, you can view the document itself jdk

Construction method

  • Date (): assignment Date object and initializes the object to indicate its assigned time (accurate to a millisecond).

  • Date (long date): Allocates a Date object and initialize the object, since the standard base time to indicate (referred to as "epoch (epoch)", namely January 1 1970 00:00:00 GMT) Specifies the number of milliseconds since .

//1、使用Date类获取当前系统时间
Date date = new Date();
System.out.println(date);
//由于Date类覆盖了toString()方法,所以可以直接输出Date类型的对象
//输出结果为Fri May 31 10:51:18 GMT+08:00 2019

/*给Date设置年份需要减去 1900
*输出结果Tue Jul 01 00:00:00 GMT+08:00 3919
*原来这里存在一个起始年份 1900,实际年份是要在你的年份参数上加上个起始年份。
*/
Date date1 = new Date(2019,5,31);
System.out.println(date1);

//2.分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。
Date date2 = new Date(System.currentTimeMillis());//参数为19701月1日以来的毫秒数
Date date3 = new Date(1559284293556l); //long类型要加l
System.out.println(date2);
System.out.println(date3);
//其他Date方法摘要可查看api

Calendar and GregorianCalendar class

java.util.Calendar class encapsulates calendar information, the main role of the time component may be in its operation method. Calendar class is an abstract class that provides a specific instant and the conversion between a group such as a calendar field YEAR, MONTH, DAY_OF_MONTH, HOUR some other method, and for manipulating the calendar fields (e.g., date of obtaining the next week) provided some method.

Because Calendar class is an abstract class, and Calendar class constructor is protected, it is impossible to use the Calendar class constructor to create objects, API provides a getInstance method used to create the object.

Java provides only java.util.GregorianCalendar java.util.Calendar this kind of implementation class, you can use the new straight out:

Calendar calendar = new GregorianCalendar();//新建出来的calendar默认时间为当前时间,或者说创建出这个对象的时间。

Calendar acquired by the static method of an instance of the method will be decided when the area from the line, to help us create a Calendar instance according to the current system where the area to note here, in fact, according to different regions, there are several sub-categories Calendar achieved. Calendar and itself is an abstract class that can not be instantiated! Specific examples of the care we do not need to create a subclass of which, we only need to use it in accordance with the method prescribed Calendar.

The fundamental problem is solved by the class calendar to simplify the calculation date, to indicate a certain date should also use the Date class description. Calendar time can be described into Date, we only need to call its getTime () method can be used to obtain a Date object date description of the.

By calculating the time-based calendar: the calendar time-based settings, set the time-based calendar using General Method set. set (int field, int value), field for the time component, Calendar provides the corresponding constant value, value for the corresponding value.

Only a month starting from 0: 0 to 1 month, and so on, 11 December, at other times it is normal from the beginning. You can also use Calendar constants calendar.NOVEMBER ...... and so on.

Calendar.DAY_OF_MONTH  月里边的天---号;
Calendar.DAY_OF_WEEK    星期里的天---星期几
Calendar.DAY_OF_YEAR     年里的天
Calendar calendar=Calendar.getInstance();//构造出来表示当前时间的日历类
Date now=calendar.getTime();//获取日历所描述的日期
calendar.set(Calendar.YEAR, 2019);//设置日历表示2019年 calendar.set(Calendar.DAY_OF_MONTH,15);//设置日历表示15号
calendar.add(Calendar.DAY_OF_YEAR, 22);//想得到22天以后是哪天
calendar.add(Calendar.DAY_OF_YEAR, -5);//5天以前是哪天
calendar.add(Calendar.MONTH, 1);得到1个月后是哪天
System.out.println(calendar.getTime());

Get the current calendar date to a time unit represented by the get method can be used.

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"年"+(month+1)+"月"+day+"日");//month要处理

SimpleDateFormat类

Common construction method

SimpleDateFormat (String pattern), pattern - to describe date and time format mode

With a given pattern and the default date format locale symbol structure SimpleDateFormat. Note: This constructor may not support all language environments. To cover all locales, use the factory methods in the DateFormat class.

Common method

public final String format(Date date)将一个 Date 格式化为日期/时间字符串
public Date parse(String source)throws ParseException从给定字符串的开始解析文本,以生成一个日期。

String Date object transformed into

//创建一个SimpleDateFormat并且告知它要读取的字符串格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = "2019-05-31";//创建一个日期格式字符串
//将一个字符串转换为相应的Date对象
Date date = sdf.parse(dateFormat);//要先捕获异常
System.out.println(date);//输出这个Date对象

Date object into a string

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
Date date = new Date(); 
String dateStr = sdf.format(date);//把日期对象传进去,继承自DateFormat类的方法。将一个Date格式化为日期/时间字符串

In the date format, - and spaces no special significance. No special meaning as they are output

//将当前系统时间转换为2012/05/14 17:05:22的效果
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
dateStr=format1.format(date);
System.out.println(dateStr);

DateFormat class

java.text.DateFormat class (abstract) SimpleDateFormat class is the parent class, with less, not SimpleDateFormat flexible.

java.sql.Date

java.sql.Date inheritance java.util.Date, to put the former into the latter, you need the following code

Date date = new Date();
//java.sql.Date 不支持Date参数的构造器,传入long类型的时间
java.sql.Date d = new java.sql.Date(date.getTime());
System.out.println(d);
System.out.println(d.getHours());

Output

2019-05-31
Exception in thread "main" java.lang.IllegalArgumentException
    at java.sql.Date.getHours(Unknown Source)
    at DateTest.DateTest1.main(DateTest1.java:40)

This is due to java.sql.Date a simple date type in SQL, not minutes and seconds. Therefore, usually by insertion java.sql.Date JDBC data , the minutes and seconds are not find. Therefore, if both the date and the time required, should be used Timestamp . It is also java.util.Date subclass, Timestamp contains complete information timestamp.

java.sql.Timestamp is java.util.Date derived class (inherited), so the java.util.Date can do, can do on java.sql.Timestamp.
If the current is 2019-06-01 14:35, you will only create a java.sql.Date this information in the record 2019-06-01. If you need to keep time for JDBC, use java.sql.Timestamp instead.

long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
timestamp.setNanos(123456);
int nanos = timestamp.getNanos(); // nanos = 123456

Now most of the Date class methods have been abandoned, it is now generally use the old API, Date only responsible for storing a time, and the Calendar and DateFormat provides operator interface. Calendar Date Get specific information, date and time of the operation, the SimpleDateFormat format of the date and time input and output.

Overall, Date, Calendar and DateFormat have been able to deal with the general problem of the date and time. But inevitably, they are still very cumbersome, difficult to use and these dates are variable and class thread safe

Joda-Time

For details, see https://www.ibm.com/developerworks/cn/java/j-jodatime.html

Java 8 date and time API

characteristic

  • Invariance: the new date / time API, all classes are immutable, it is very good for multi-threading.
  • Separation of concerns: learning from some of the advantages Joda library, the new API will be human-readable date and time and machine time (unix timestamp) a clear separation, which is the date (Date), time (Time), the date and time (DateTime), timestamp (unix timestamp) and zoning defines different classes.
  • Clear: In all classes, methods are clearly defined in order to accomplish the same behavior. For example, to get the current instance, we can use now () method, in all the classes are defined in the format () and parse () method, rather than have a separate special class as before. In order to better deal with the problem, all classes use the factory pattern and strategy pattern, once you use a method in a class, and other types of work is not difficult.
  • Practical Operation: All new date / time API class implements a number of methods to perform common tasks, such as: addition, subtraction, formatting, resolution, a separate part from the extracted date / time, and the like.
  • Scalability: The new date / time API works in ISO-8601日历系统上的, but we can also be used in non-IOS calendar.

Java8日期时间的默认格式如下: yyyy-MM-dd-HH-mm-ss.zzz

Several major core classes:

  • LocalDate: Date class, with no time
  • LocalTime: class time, with no date
  • LocalDateTime: date and time classes
  • ZonedDateTime: Time zone Date Time Class
  • OffsetDateTime: UTC time offset obtained by the date and time
  • Clock: Get the current instantaneous time in a time zone, date or time
  • Instant: Unix time, on behalf of the timestamp, such as 2018-01-14T02:20:13.592Z
  • Duration: between two time span represents an absolute accuracy, using milliseconds
  • Period: between two dates
  • ZoneId: Time zone
  • DateTimeFormatter: formatted output
  • TemporalAdjusters: get the specified date and time, as the first day of the month, the last day of the year, etc.

Let's look at how to use these specific classes

LOCALDATE, localtime, my localdateti

LocalDate not change the date and time object represents a date, often regarded as the date. Other date fields, such as day of the year, week and day of the week, can also be accessed. For example, the value "2 October 2007" may be stored in a LocalDate.

LocalTime not change the date and time object represents a time, often seen as hours minutes seconds. Time as the representative of nanosecond accuracy. For example, the value "13: 45.30.123456789" can be stored in a LocalTime.

LocalDateTime not change the date and time object represents a date and time, often seen as year, month, day, hour, minute and second. Other date and time fields, such as day of the year, week and day of the week, can also be accessed. Time as the representative of nanosecond accuracy. For example, the value of "October 2, 2007 at 13: 45.30.123456789" can be stored in a LocalDateTime.

//now()在默认时区中从系统时钟获取当前日期。
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); //等价于 today.plusWeeks(1)

//of(int year, int month, int dayOfMonth) 获得 LocalDate实例从一年、月、日。 
LocalDate date = LocalDate.of(2019,5,31);
LocalTime time = LocalTime.of(20,31,20);

//of(LocalDate date, LocalTime time) 获得 LocalDateTime实例的日期和时间。 
LocalDateTime dateTime = LocalDateTime.of(date,time);
System.out.println(dateTime);

//LocalDate结合LocalTime成一个LocalDateTime
LocalDateTime dateTime2 = date.atTime(time);
System.out.println(dateTime2); //2019-05-31T20:31:20

DateTimeFormatter

Date string formatter for parsing and formatting output date format is the easiest way to create a static factory method and by the DateTimeFormatter constants. Create a format generally has the following three ways:

  1. Conventional ISO format constants, such as ISO_LOCAL_DATE
  2. Alpha mode, as ofPattern ( "yyyy / MM / dd")
  3. Localization style, such as ofLocalizedDate (FormatStyle.MEDIUM)

And the old java.util.DateFormat compared to all DateTimeFormatter instances are thread safe.

Use DateTimeFormatter complete format

//获取默认时区中从系统时钟获取当前日期时间。
LocalDateTime localDateTime = LocalDateTime.now();
//创建一个格式化程序使用指定的模式。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = localDateTime.format(formatter);
System.out.println(formatDateTime);

//DateTimeFormatter提供了一些默认的格式化器,DateTimeFormatter.ISO_LOCAL_DATE_TIME 格式 yyyy-MM-ddTHH:mm:ss.SSS
String dateTime2 = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(dateTime2);

Using the string has been parsed DateTimeFormatter

//获得 LocalDate实例,从使用特定格式的文本字符串解析,文字使用格式化程序解析,返回一个日期。
LocalDate localDate = LocalDate.parse("2018/11/11",DateTimeFormatter.ofPattern("yyyy/MM/dd"));
System.out.println(localDate); //2018-11-11

Instant

Instant represent a little timeline (Date and similar), it simply represents the number of seconds since at 0:00:00 on January 1, 1970 (UTC) began.

Instant consists of two parts, one from the origin to the given point in time s seconds, two seconds is the number of the distance s of nanoseconds. It is stored as a Unix timestamp date and time does not provide the processing unit of time on the human sense (the date, etc.).

You can create an instance by Instant Instant class factory method

//调用instant.now()来创建一个确切的表达当前时间的Instant对象.另外也有一些其它方法能创建Instant,具体请查阅Java官方文档。
Instant now = Instant.now();
Instant later = now.plusSeconds(3);
Instant earlier = now.minusSeconds(3);

//第一个参数是秒,第二个是纳秒参数,纳秒的存储范围是0至999,999,999
//2s之后的在加上100万纳秒(1s)
Instant instant = Instant.ofEpochSecond(2,1000000000);
System.out.println(instant); //1970-01-01T00:00:03Z

Instant instant1 = Instant.now();
System.out.println(instant1); //2019-05-31T16:19:28.719Z

Instant instant2 = Instant.parse("2018-11-11T10:12:35.342Z");
System.out.println(instant2); //2018-11-11T10:12:35.342Z

//java.util.Date与Instant可相互转换
Instant timestamp = new Date().toInstant();
Date.from(Instant.now());

//为了更好的显示,代码改写为
Date date = new Date();
Instant timestamp = date.toInstant();
System.out.println(date);
System.out.println(timestamp);
Instant now1 = Instant.now();
Date date1 = Date.from(now1);
System.out.println(now1);
System.out.println(date1);
//输出结果
Sat Jun 01 00:29:42 GMT+08:00 2019
2019-05-31T16:29:42.566Z
2019-05-31T16:29:42.588Z
Sat Jun 01 00:29:42 GMT+08:00 2019

Clock

Clock used to find the current time, can be used to get the current date and time in a time zone can also be used to replace the old System.currentTimeMillis () method and TimeZone.getDefault () method.

//返回系统默认时间
Clock clock = Clock.systemDefaultZone();
System.out.println(clock.instant().toString());

//世界协调时UTC
Clock clock = Clock.systemUTC();  
//通过Clock获取当前时刻  
System.out.println("当前时刻为:" + clock.instant());  
//获取clock对应的毫秒数,与System.currentTimeMillis()输出相同  
System.out.println(clock.millis());  
System.out.println(System.currentTimeMillis());  

Duration

Duration is an immutable instance, when after the object can not create a change its value. You can only calculation method Duration of to create a new Durtaion object. You will see the following tutorial. Duration object represents a period of time between two Instant.

Duration created instance, using factory method to create a class Duration Duration object

Instant first = Instant.now();
// wait some time while something happens
Instant second = Instant.now();
Duration duration = Duration.between(first, second);

//获得Duration表示秒数,然后获得在此期间的分钟数、小时数、天数
Duration d = Duration.ofSeconds(6000);  
System.out.println("6000秒相当于" + d.toMinutes() + "分");  
System.out.println("6000秒相当于" + d.toHours() + "小时");  
System.out.println("6000秒相当于" + d.toDays() + "天");  

Duration time access
a Duration object has two fields: nanosecond value (less than one second part), seconds (a total of several seconds), the combined expression of their duration. Note that using System.getCurrentTimeMillis (time) different, Duration milliseconds does not contain this attribute.
You can get their values by the following two methods: getSeconds () and getNano ()

Period

Period date is to measure a time period for calculating the two dates, so BETWEEN () method can only receive LocalDate type parameter.

LocalDate start = LocalDate.of(2018, Month.JANUARY, 1);
LocalDate end = LocalDate.of(2020, Month.NOVEMBER, 11);
System.out.println("相隔月数:"+Period.between(start, end).getMonths());
System.out.println("相隔天数:"+Period.between(start, end).getDays());
//输出结果
相隔月数:10
相隔天数:10

Notably, Period absolute differences is obtained (corresponding date direct mathematical calculation of the difference), but does not indicate the true interval distance .

long distanceMonth = start.until(end, ChronoUnit.MONTHS);
long  distanceDay= start.until(end, ChronoUnit.DAYS);
System.out.println("相隔月数"+distanceMonth);
System.out.println("相隔天数"+distanceDay);
//输出结果
相隔月数:34
相隔天数:1045

ZonedDateTime和ZonedId

ZonedDateTime class is the Java 8 date and time functions, the type of date and time zone information for indicating the tape. ZonedDateTime value class is immutable, so the calculation method returns a new instance ZonedDateTime.

Java uses ZoneId to identify different time zones, a fixed offset from the beginning of the UTC reference.

Create an instance of ZonedDateTime

//使用当前时间作为值新建对象
ZonedDateTime dateTime = ZonedDateTime.now();

//使用指定的年月日、时分、纳秒以及时区ID来新建对象
//时区是用ZoneId类表示的,可以使用ZoneId.now()或ZoneId.of(“xxx”)来实例化:
//传给of()方法的参数是时区的ID,如“UTC+1”指距离UTC(格林威治时间)有一小时的时差
ZoneId zoneId = ZoneId.of("UTC+1");
ZonedDateTime dateTime2 = ZonedDateTime.of(2019, 6, 1, 14, 40, 48, 1234, zoneId);

//也可以使用另一种方式表示zone id,即使用地区名字
ZoneId zoneId2 = ZoneId.of("Europe/Copenhagen");

//GregorianCalendar与ZonedDateTime相互转换
ZonedDateTime zonedDateTime = new GregorianCalendar().toZonedDateTime();
GregorianCalendar.from(zonedDateTime);

TemporalAdjusters

Sometimes, you need to do some more complex operations, such as the change of date to next Sunday, the next working day, or the last day of the month.

Simple application example

LocalDate localDate = LocalDate.now();  
// 1. 本月第一天
LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
// 2. 本月最后一天
LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
// 3. 本年第一天
LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
// 4. 下个月第一天
LocalDate firstDayOfNextMonth = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
// 5. 本年度最后一天
LocalDate lastDayOfYear = localDate.with(TemporalAdjusters.lastDayOfYear());
System.out.println(firstDayOfMonth);
System.out.println(lastDayOfMonth);
System.out.println(firstDayOfYear);
System.out.println(firstDayOfNextMonth);
System.out.println(lastDayOfYear);

At this point, you can use the overloaded version with the method , passing it provides a more customized selection of TemporalAdjuster objects, greater flexibility in dealing with dates. TemporalAdjusters class provides a number of commonly used TemporalAdjuster achieved through the static methods for our use.

/**
 * 时间校正器TemporalAdjuster
 */
@Test
public void Test() {
    LocalDateTime now1 = LocalDateTime.now();
    //获取月中的第一天
    now1.with(TemporalAdjusters.firstDayOfMonth());
    //获取下一年的第一天   
    now1.with(TemporalAdjusters.firstDayOfNextYear());
    //获取年中第一天
    now1.with(TemporalAdjusters.lastDayOfYear());
    //获取月中最后一天
    now1.with(TemporalAdjusters.lastDayOfMonth());
    //获取下个星期一
    now1.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
    //自定时时间:下一个工作日,因为这里需要一个接口,所以完全可以自定义方法
    now1.with((e) -> {
        LocalDateTime now = (LocalDateTime)e; 
        DayOfWeek dow = now.getDayOfWeek();
        if (dow.equals(DayOfWeek.FRIDAY)) 
            return now.plusDays(3);
        else if (dow.equals(DayOfWeek.SATURDAY))
            return now.plusDays(2);
        return  now.plusDays(1);
    });
}

Change

java.util.Date and LocalDate, LocalTime, LocalDateTime conversion

Is converted to the Date LocalDate, LocalTime, LocalDateTime by means ZonedDateTime and Instant, implemented as follows:

Date date = new Date();
System.out.println("current date: " + date);

// Date -> LocalDateTime
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("localDateTime by Instant: " + localDateTime);

// Date -> LocalDate
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("localDate by Instant: " + localDate);
// Date -> LocalTime
LocalTime localTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
System.out.println("localTime by Instant: " + localTime);

//2. Date -> LocalDateTime
localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
System.out.println("localDateTime by ofInstant: " + localDateTime);

Since JDK8 achieve backward compatibility, so Date in the JDK8 release introduces two methods, from and
toInstant, so we can use these two methods to achieve the conversion of LocalDateTime to Date. The LocalDateTime into Date as follows:

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime: " + localDateTime);

// LocalDateTime -> Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("LocalDateTime -> current date: " + date);

// LocalDate -> Date,时间默认都是00
LocalDate localDate = LocalDate.now();
date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println("LocalDate -> current date: " + date);

Date and string conversion

By LocalDate, LocalTime, LocalDateTime parse method and DateTimeFormatter to achieve:

//字符串->日期
LocalDate localDate = LocalDate.parse("2018-09-09", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime localDateTime = LocalDateTime.parse("2018-09-10 12:12:12", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

//日期->字符串
String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String localDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 也可以通过DateTimeFormatter的format方法
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
localDateTime = dateTimeFormatter.format(LocalDateTime.now());

Timestamp conversion LocalDateTime

Specific achieve the following:

//时间戳->LocalDateTime
public static LocalDateTime convertToDate(long timestamp) {
   // ofEpochSecond 以秒为单位, ofEpochMilli 以毫秒为单位
   // Instant.ofEpochSecond(timestamp);
   Instant instant = Instant.ofEpochMilli(timestamp);
   return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}

//LocalDateTime->时间戳
public static long convertToTimestamp() {
   LocalDateTime localDateTime = LocalDateTime.now();
   return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}

to sum up

  • All new date and time API class implements a number of methods to perform common tasks, such as: addition, subtraction, formatting, resolution, a separate part from the extracted date / time.
  • Java 8 in a new time and date for all classes in the API are immutable and thread-safe, any modification operation will return a new instance.
  • The new date and time API to distinguish between various concepts and each concept using a similar method definition mode, this similarity is very conducive to learning API. Summarize the general approach or method prefix:
    • of: static factory methods for creating instances
    • now: static factory method, create an instance with the current time
    • parse: a static factory method, obtained from the string parsing object instance
    • get: get partial state the date and time of the object.
    • is: checking whether something is true, for example, comparing before and after the time
    • with: returns a state change part of the date and time copy of the object
    • plus: Returns a time increases, the date and time copy of the object
    • minus: Returns a reduced time, the date and time copy of the object
    • to: switch to another type
    • at: this object with another object in combination, e.g. date.atTime (time)
    • format: the ability to provide date and time formatting objects

More ways to use please refer to the Java api documentation

Reference article:

http://www.importnew.com/14140.html

https://docs.oracle.com/javase/8/docs/api/

https://www.jianshu.com/p/f4abe1e38e09

Guess you like

Origin www.cnblogs.com/kiwenzhang/p/10960742.html