Dates and APIs

Source: Internet
Author: User
Tags date1 dateformat time zones

Java1.0 support for dates and times can only depend on the Java.util.Date class, the start of the year is 1900 you, the beginning of the month is calculated from 0. Its return value contains the default urban CET for the JVM, which is central European time. Use the Java.util.Calendar class instead of date in Java1.1. DateFormat that both format and parse dates exist only in date, and threads are unsafe. Both date and calendar are mutable. JAVA8 integrates many joda-time features in the java.time.

The Java.time provides localdate,localtime,instant,duration and period.

  

Localdate and LocalTime

Examples of localdate and localtime are immutable objects, Localdate provides only simple dates, does not contain time information for the current day, and does not come with any time zone-related information. The localtime only provides time.

Temporalfield is an interface that defines the value of a field that accesses a temporal object. The Chronofield enumeration implements this interface, and you can use Localdate.get (Chronofield) to get the value of an enumeration element.

int year = Localdate.now (). get (Chronofield.year);

Both Localdate and localtime can parse the string creation that represents them through the parse () method. You can also pass a datetimeformatter to the parse () method, which is a replacement for Java.util.DateFormat. The two parse methods will throw a Datetimeparseexception exception once the passed string argument cannot be parsed into a legitimate localdate or LocalTime object.

Localdate date = Localdate.parse ("2017-07-24");

LocalTime time = Localtime.parse ("12:25:05");

LocalDateTime

LocalDateTime is a combination of localdate and localtime, indicating the date and time, but without the time zone. You can localdate and localtime can create a LocalDateTime object through the Attime () and Atdate () methods, or call LocalDateTime's Tolocaldate () and ToLocalTime () method to generate Localdate and LocalTime objects.

LocalDateTime dateTime = Localdatetime.of (, month.july, 24, 11, 11, 11);
Localdate date = Localdate.now ();
LocalTime time = Localtime.now ();
LocalDateTime dateTime1 = localdatetime.of (date, time);
LocalDateTime dateTime2 = date.attime (11, 11);
LocalDateTime DateTime3 = Date.attime (time);
LocalDateTime dateTime4 = time.atdate (date);
Localdate date1 = Datetime.tolocaldate ();
LocalTime time1 = Datetime1.tolocaltime ();

From the computer's point of view, the most natural form of modeling time is a single large integer representing a point on a duration period. The way the Java.time.Instant class models time is calculated as the number of seconds that the UNIX has experienced in the first time. You can create an instance of the class by passing a static factory method Ofepochsecond A value that represents the description, and it can also receive the second parameter value in seconds, adjusting the parameters passed in as described. The overloaded version adjusts the nanosecond parameter to ensure that the saved nanosecond shards are adjusted in 0 to 999999 of the parameters passed in as the number of seconds. The instant class supports the static factory method now, which can help you get the timestamp of the current moment.

Instant.ofepochsecond (3);

Instant.ofepochsecond (2, 1000000000); 2s plus 1s

Instant.ofepochsecond (2,-1000000000); 2s ago 1s

Duration or period

The temporal interface defines how to read and manipulate the values of the objects that are modeled for time. The static factory between of the Duration class can calculate duration between two temporal objects.

Duration D1 = Duration.between (time1, time2);

Duration D2 = Duration.between (datetime1, datetime2);

Duration d3 = Duration.between (Instant1, instant1);

If you attempt to create a duration between instant and LocalDateTime objects, the datetimeexception exception is triggered.

If you need to model multiple times in years, months, or days, you can use the period class.

Period tendays = Period.between (Localdate.of (2014, 3, 18)), Localdate.of (3);

  

Static between creates a interval between two points in time

The static from is created by a temporary point in time interval

Static of the interval instance created by its components

Static Parse creates an instance of interval from a string

AddTo creates a copy of the interval and overlays it to a specified temporal object

Get reads a copy of the interval and overlays it to a specified temporal object

Isnegative checks if the interval is negative and does not contain 0

Iszero Check whether the interval is often 0

Minus creates a copy of the interval by subtracting a certain amount of time

Multipliedplay to multiply the value of interval by a scalar to create a copy of the interval

Negated create the interval copy in a way that ignores a certain amount of time

Plus creates a copy of the interval in a way that adds a specified amount of time

Substractfrom subtracts the interval from the specified temporal object

  

The simplest way to create a modified version of a Localdate object is to Withattribute the method. The Withattribute method creates a copy of the object and modifies its properties as needed. By using the Get and with methods, you can separate the read and modify temporal object values. If the temporal object does not support the requested access field, it throws a Unsupportedtemporaltypeexception exception.

Localdate date1 = Localdate.of (2014, 3, 18);

Localdate date2 = date1.withyear (2011);

Localdate Date3 = Date2.withdayofmonth (25);

Localdate date4 = Date3.with (chronofield.month_of_year, 9);

A common method for date-time classes that represent points in time

Static from creates an object instance from an incoming temporal object

Static now creates temporal objects based on system clock

Static of tin plated by temporal you've loved a part of you. Create an instance of the object

Static Parse creates an instance of the temporal object from a string

Atoffset combining the Temporal object with a time zone offset

Atzone combining the Temporal object with a time zone

Format converts a Temporal object to a string using a specified format

Get reads the value of a part of a temporal object

Minus creates a copy of the temporal object by subtracting the value of the current temporal object by a certain amount of time to create the copy

Plus creates a copy of the temporal object, creating the copy by adding the value of the current temporal object to a top length

With the temporal object as a template, modify some states to create a copy of the object

Temporaladjuster

The with method of Localdate can accept a Temporaladjuster object.

Localdate date1 = Localdate.of (2014, 3, 18);

Localdate date2 = Date1.with (Nextorsame (dayofweek.sunday));

Factory methods in the Temporaladjuster class

Dayofweekinmonth creates a new date whose value is the day ordinal of the week in the same one month

Firstdayofmonth creates a new date whose value is the first day of the month

Firstdayofnextmonth creates a new date whose value is the first day of next month

Firstdayofnextyear creates a new date, its value is the first day of next year

Firstdayofyear creates a new date whose value is the first day of the year

Firstinmonth creates a new date whose value is the first day of the month

Lastdayofmonth creates a new date whose value is the last day of the month

Lastdayofnextmonth creates a new date whose value is the last day of the next month

Lastdayofnextyear creates a new date, its value is the last day of next year

Lastdayofyear creates a new date with a value of the last day of the year

Lastinmonth creates a new date with a value of the same one month, the last one that meets the day of the week

Next/previous Create a new date and set it to the date after the date is adjusted or adjusted before the first one meets the specified week requirement

Nextorsame/previousorsame Create a new date and set its value to date adjusted or adjusted before the first date that meets the specified day of the week, and if that date has been met, return the object directly

  

@FunctionalInterface

public interface temporaladjuster{

Temporal adjustinto (temporal temporal);

}

  

 Public classNextworkingdayImplementstemproaladjuster{ Publictemporal adjustinto (temporal temporal) {DayOfWeek Dow=Dayofweek.of (Temporal.get (Chronofield.day_of_week)); intDayofadd = 1; if(Dow = =dayofweek.friday) Dayofadd= 3; Else if(Dow = =dayofweek.saturday) {Dayofadd= 2; }    returnTemporal.plus (Daytoadd, chronounit.days); }}date= Date.with (Temporal- {     Publictemporal adjustinto (temporal temporal) {DayOfWeek Dow=Dayofweek.of (Temporal.get (Chronofield.day_of_week)); intDayofadd = 1; if(Dow = =dayofweek.friday) Dayofadd= 3; Else if(Dow = =dayofweek.saturday) {Dayofadd= 2; }    returnTemporal.plus (Daytoadd, chronounit.days);}); Temporaladjuster Nextworkingday=Temporaladjuster.ofdateadjust (Temporal-{DayOfWeek Dow=Dayofweek.of (Temporal.get (Chronofield.day_of_week)); intDayofadd = 1; if(Dow = =dayofweek.friday) Dayofadd= 3; Else if(Dow = =dayofweek.saturday) {Dayofadd= 2; }    returnTemporal.plus (Daytoadd, chronounit.days);}); Date= Date.with (Nextworkingday)

Java.time.format is used for formatting and parsing date-time. The DateTimeFormatter instance is used to create a string that represents a specific date or time in a certain format, and is thread safe.

Localdate date = Localdate.of (2017, 8, 9);

String S1 = Data.format (datetimeformatter.basic_iso_date); 20170809

String s2 = Data.format (datetimeformatter.iso_local_date); 2017-08-09

Localdate date1 = Localdate.parse ("20170809", datetimeformatter.basic_iso_date);

The Datetimeformatter.ofpattern () method can create a formatter in a specific pattern, and the Ofpattern () method can also create a formatter for a locale

DateTimeFormatter formatter = Datetimeformatter.ofpattern ("dd/mm/yyyy");

DateTimeFormatter Italianformatter = Datetimeformatter.ofpattern ("D. MMMM yyyy", Locale.italian);

    

The purpose of java.time.ZoneId is to make it unnecessary for you to deal with complex and cumbersome time zones. The specified urban rules are obtained by calling Zoneid.getrules (). Each specific ZoneID object is identified by a region ID.

ZoneID Romezone = Zoneid.of ("Europe/rome");

The region ID is in the "area/city" format, and the settings for these regional collections are provided by the time zone database of the Internet number allocation agency IANA. You can convert an old time zone object to ZoneID through Tozoneid. ZoneID integration with Localdate,localdatetime or instant to get Zoneddatetime instances

ZoneID ZoneID = Zoneid.getdefault (). Tozoneid ();

Localdate date = Localdate.of (Month.march, 10);

Zoneddatetime ZDT = Date.atstartofday (ZoneID);

LocalDateTime datetime = Localdatetime.of (Month.march, 10, 18, 13, 45);

ZDT = Datetime.atzone (Romezone);

Instant Instant = Instant.now ();

ZDT = Instant.atzone (Romezone);

Instant instantfromdatetime = datetime.toinstant (Romezone);

LocalDateTime datetimefrominstant = localdatetime.ofinstant (instant, romezone);

The ISO-8601 calendar system is the implementation standard of the World civilized calendar system. JAVA8 also offers 4 other calendar systems. They are thaibuddhistdate,minguodate,japanesedate and hijrahdate, respectively. These classes and localdate all implement the Chronolocaldate interface.

Localdate date = Localdate.of (Month.march, 10);

Japenesedate JDate = japenesedate.from (date);

Chronology japanesechronology = Chronology.oflocale (Locale.janpan);

Chronolocaldate now = Japanesechronology.datenow ();

Dates and APIs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.