java8 Time API Introduction and use

java7 And previous versions , Recommended jodatime
java8 Provided datetime api Refer to the jodatime

At a new time API in ,

Instant Represents a precise point in time ,

Duration and Period Represents the amount of time between two time points . 
LocalDate Indicates the date , namely xx year xx month xx Japan ,

Neither time nor time zone .LocalTime And LocalDate similar .

LocalDateTime Include the date and time .

OffsetDateTime Represents a band ZoneOffset Time for .

ZoneDateTime Represents a time with a time zone . 
DateTimeFormatter Provides formatting and parsing functions .

java8 Time for api There are many on the Internet , Not in detail .

The picture below is from Baidu :

Because the project needs , Time needs to be transformed into GMT Format , Time format with time zone

The timestamps of different time zones at the same time are the same , That is, timestamps are all different time zones relative to 1970 The absolute value of the interval between years ,2016-10-10T20:00:00.000+1:00 And 2016-10-10T23:00:00.000+4:00 It's the same time stamp , At the same time . So let's talk about string Time string conversion of type long And then format it into different time zones .

The following tool classes are for reference only :

public class OffsetDateTimeTool {
//private static final ZoneOffset OFFSET_ID = ZoneOffset.of("+08:00");
private static final ZoneOffset OFFSET_ID = getOFFSET_ID();
/**
* String turn OffsetDateTime
*/
public static String getZoneStringDateTime(CharSequence text){
return formatDateTime(OffsetDateTime.of(LocalDateTimeTool.parseTime(text.toString()),OFFSET_ID)
,TimeFormat.LONG_DATE_PATTERN_WITH_TIME_ZONE.value());
}
/**
* String turn OffsetDateTime turn long turn OffsetDateTime format String
*/
public static String getStringDateTime(CharSequence text) {
return formatDateTime(OffsetDateTime.ofInstant(Instant.ofEpochMilli(getLongDateTime(text
,TimeFormat.LONG_DATE_PATTERN_WITH_TIME_ZONE.value(),getOffset(text.toString()))),OFFSET_ID)
,TimeFormat.LONG_DATE_PATTERN_LINE.value());
}
/**
* String turn OffsetDateTime turn long
*/
public static long getLongDateTime(CharSequence text, String patten, String offsetId) {
return getLong(parse(text,patten,offsetId))*1000;
}
/**
* OffsetDateTime turn long
*/
public static long getLong(OffsetDateTime offsetDateTime) {
return offsetDateTime.getLong(ChronoField.INSTANT_SECONDS);
}
/**
* Set the date based on the string
*
* @return OffsetDateTime
*/
public static OffsetDateTime parse(CharSequence text, String patten, String offsetId) {
LocalDateTime localDateTime = LocalDateTime.parse(text, DateTimeFormatter.ofPattern(patten));
return OffsetDateTime.of(localDateTime, ZoneOffset.of(offsetId));
}
/**
* Format time
*/
public static String formatDateTime(OffsetDateTime dateTime, String patten) {
return dateTime.format(DateTimeFormatter.ofPattern(patten));
}
/**
* Get the system time zone
*/
public static ZoneOffset getOFFSET_ID(){
return LocalDateTime.now(ZoneOffset.systemDefault()).atZone(ZoneOffset.systemDefault()).getOffset();
}
/**
* obtain string The time zone
*/
public static String getOffset(String date){
return date.substring(date.length()-6,date.length());
}
/**
* Get the current time stay ISO-8601 In the calendar system UTC / Greenwich offset date time , Such as 2017-12-03T10:15:30+08:00
*/
public static OffsetDateTime getDateTimeNow() {
return OffsetDateTime.now();
}
/**
* Acquisition time ( Just set the date )
*/
public static OffsetDateTime getDateTime(int year, int month, int day , String offsetId) {
return getDateTime(year, month, day, 0, 0, 0, 0 , ZoneOffset.of(offsetId));
}
/**
* Acquisition time
*
* @param year
* year
* @param month
* month
* @param day
* Japan
* @param hour
* when
* @param minute
* branch
* @param second
* second
* @param nanoOfSecond
* nanosecond
* @param zoneOffset
* The time zone
* @return OffsetDateTime
*/
public static OffsetDateTime getDateTime(int year, int month, int day, int hour, int minute, int second,
int nanoOfSecond, ZoneOffset zoneOffset) {
return OffsetDateTime.of(year, month, day, hour, minute, second, nanoOfSecond, zoneOffset); }
/**
* Inner enumeration class
*/
public enum TimeFormat {
// Short time format Specific date
/**
* Time format :yyyy-MM-dd HH:mm:ss
*/
LONG_DATE_PATTERN_LINE("yyyy-MM-dd HH:mm:ss"), LONG_DATE_PATTERN_WITH_TIME_ZONE("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
private String value = ""; TimeFormat(String value) {
this.value = value;
} public String value() {
return this.value;
}
}
public static void main(String args[]) {
System.out.println("getLongDateTime : "
+ getLongDateTime("2018-06-05T08:00:00.000+08:00"
,TimeFormat.LONG_DATE_PATTERN_WITH_TIME_ZONE.value(),getOffset("2018-06-05T04:00:00.000+08:00") ));
System.out.println("getLongDateTime : "
+ getLongDateTime("2018-06-05T04:00:00.000+04:00"
,TimeFormat.LONG_DATE_PATTERN_WITH_TIME_ZONE.value(),getOffset("2018-06-05T04:00:00.000+04:00") ));
System.out.println("getStringDateTime :" + getStringDateTime("2018-06-05T04:00:00.000-12:00"));
System.out.println("getZoneStringDateTime:" + getZoneStringDateTime("2018-06-05 04:00:00"));
}
}

OffsetDateTime More articles on tools

  1. Java8 ,LocalDate,LocalDateTime Processing date and time tool class ,

    Java8 ,LocalDate,LocalDateTime Processing date and time tool class 1. Get today's date 2. stay Java 8 Get the year . month . Daily information 3. stay Java 8 Processing specific dates 4. stay Java 8 ...

  2. Java Basics Map Interface +Collections Tool class

    1.Map We mainly talk about two interfaces HashMap  And    LinkedHashMap (1) among LinkedHashMap Is ordered   How to save and how to take out Let's talk about Map The function of adding, deleting, modifying and checking : /* * Ma ...

  3. Android— About the tool class of custom dialog box

    There are many places to use custom dialog box in development , To avoid unnecessary city code , Here is a tool class . There are many places where the dialog box pops up , But it's all the same , The difference is nothing more than the prompt content or picture , The following class puts the prompt content and picture into the user defined function ...

  4. [ turn ]Java Common tool class collection

    from :http://blog.csdn.net/justdb/article/details/8653166 Database connection utility class —— Just get the connection object ConnDB.java package com.ut ...

  5. js Common tools .

    some js Tool class of Copy code /** * Created by sevennight on 15-1-31. * js Common tools */ /** * Method function :[ Format time ] * Usage method * Example : * ...

  6. Guava Library introduces the utility class

    author :Jack47 Please keep the author and the source of the original Welcome to my wechat public account programmer Jack , The articles on both sides will be synchronized , You can also add my RSS Feeds . I wrote this article Google Open source Java Programming library Guava One of series , Main introduction ...

  7. Java Programmer's daily —— Arrays Use of tool class

    This class is used in daily development , It's still very common . Let's summarize today Arrays Common methods of tool class . The most common is asList,sort,toStream,equals,copyOf 了 . In addition, we can further study Arrays My platoon ...

  8. .net Use regular expression validation 、 Match character tool class

    Development program cannot do without data verification , Here are some data checks . Matching method : /// <summary> /// character ( strand ) verification . Match tool class /// </summary> public c ...

  9. WebUtils- Network request tool class

    Network request tool class , Big code reference aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

Random recommendation

  1. php-into Various problems encountered during installation ,php -m Follow phpinfo() Inconsistent display

    System environment Aliyun server ubuntu nginx php5.4.23 stay Yii2 The user is displayed in the format currency, So we need to intl modular , There's nothing to say about it . apt-get install libicu-de ...

  2. CentOS Source Ubuntu Source OpenSUSE----- Keep summarizing

    CentOS Basics ( Commonly used ) Source :http://dl.fedoraproject.org/pub/epel/epel-release-latest-5.noarch.rpmhttp://dl.fedor ...

  3. panel,dialog,window Summary of component out of bounds problems

    I have written before panel,dialog,window Three components because of dragging or reSize This causes the component to be out of bounds and cannot be restored , Two articles on drag and reSize The solution is given . But according to feedback from friends ,reSize The solution of the ...

  4. Using software nginx Realization web Server cluster

    nginx: Software load balancer   It's high concurrency http/ Reverse proxy . Realization windows Next IIS Load balancing of Conditions :2 Servers 1.cpu:Inter(R) core i5 cpu 2.26GHz Memory :2G ...

  5. JQuery verification input

    jsp The form is as follows : <form method="post" action="AddPlayer"> <div class = "on ...

  6. php Basics ( 6、 ... and )Include

    The content of this article comes from http://www.w3school.com.cn/php/php_file.asp Server side contains (SSI) Used to create functions that can be reused in multiple pages . header . Footer or element . include ( ...

  7. JavaScript solve select The content in the drop-down box is too long to display completely

    JavaScript solve select The content in the drop-down box is too long to display completely 1. explain In some cases ,select The content of the drop-down box is too long , Cause part of it to be invisible : Now through the mouse event , Let the contents in the drop-down box display completely 2. Implementation source code & ...

  8. MongoDB Document operations in ( Two )

    One . Inserted into the document 1.db. Collection name .insert() Insert a :db.user.insert({name:"Join",age:13,address:"beijing& ...

  9. SpringBoot series ——MyBatis Integrate

    Preface MyBatis Official website :http://www.mybatis.org/mybatis-3/zh/index.html This paper records springboot And mybatis Integration examples of :1. In the form of annotations :2. Handwriting ...

  10. 【Linux】Jenkins install ( Two )

    Jenkins Introduce Jenkins Is based on Java A continuous integration tool for development , Used to monitor continuous repetitive work , Features include : 1. Continuous software release / Test project . 2. Monitoring work performed by external calls . Installation environment operating system :lin ...