Android Basics
Android Skill Tree – Fragment overview
Android Skill Tree – Animation summary
Android Skill Tree – View summary
Android Skill Tree – Activity summary
Android Skill Tree – View event system summary
Android Skill Tree – Summary of Android storage paths and I/O operations
Android Skill Tree – Multi-process related summary
Android skill Tree – Drawable summary
Android Skill Tree – Screen Adaptation summary
Preface:
It is found that many developers have their own methods when dealing with time-related problems, and the knowledge of various Java time-related classes is not very clear. Sometimes we see that they use them at the same time during development, and then temporarily search to deal with time-related problems.
Let’s say you’re asking for the length of a song, and the background returns you 00:03:06, and you need to use the total number of seconds in your code, and you’re asking how do you get that to a specific number of seconds. In the existing project, I see the processing code for this looks like this:
if (min.contains(":")) {
String[] items = min.split(":");
duration += (Integer.valueOf(items[0]) * 60 * 60 * 1000 + Integer.valueOf(items[1]) * 60 * 1000 + Integer.valueOf(items[2]) * 1000);
}
Copy the code
There’s nothing wrong with the above code, of course, but we could have handled it with time-dependent classes.
Body:
1. Time acquisition
Since speaking of time-related knowledge, the most important thing is to acquire time.
1.1 the Date:
In fact, the brain map is already very detailed, and we will not be super familiar with the Date, so we just pick a few points to say:
Constructor:
Date date = new Date(); // Use toString() to display the current date.tostring (); //Sat Aug 31 15:20:08 CST 2019 Date date1 = new Date(1000); //1970.01.01 00:00:00 start date1.toString(); //1970.01.01 00:00:00 start date1.tostring (); //Thu Jan 01 08:00:01 CST 1970Copy the code
Get/set function:
Date date = new Date(); // Get the difference between the current Date and 1970.01.01 08:00:00'The actual Date represents the time difference between 1970.01.01 and 00:00:00. Because it is currently the east 8 sector, we get 08:00:00'.date.getTime(); //1567576587763 Date date1 = new Date(1000); date1.getTime(); //1000 Date date2 = new Date(); date2.setTime(1000); date2.getTime(); / / 1000Copy the code
Two Date comparison functions:
Date aaaaa = new Date(1000); Date bbbbb = new Date(2000); aaaaa.after(bbbbb); //falseaaaaa.before(bbbbb); //trueaaaaa.equals(bbbbb); //falseaaaaa.compareTo(bbbbb); If a<b, a==b, b = 0, a>b, b = 1Copy the code
1.2 the Calendar:
We know that Date can represent the time value (because with Date, we can obtain the difference between 1970-01-01 08:00:00 and the current time).
Therefore, Calendar not only provides the method of returning long type when obtaining time, but also provides the method of returning Date object when obtaining time
Get time:
Calendar cl = Calendar.getInstance(); Date date = cl.getTime(); // Get the Date object cl.getTimeInmillis (); Date.gettime () is the same as cl.getTimeinmillis ()Copy the code
Of course, Calendar can also take specific values such as year, month, day, hour, minute and second:
For example, get the hour of the current time: Calendar cl = calendar.getInstance (); Cl.get (calendar.hour_of_day)); 16 / /'Notice that you get Mouth from 0, like it's September, you get 8.'cl.get(Calendar.MONTH); / / 8Copy the code
There are many specific parameters, you can choose:
Setting time:
Get time, set time is the same, you can directly set the type of long, can also set the type of Date, can also directly set the specific year, month and day field value.
public final void setTime(Date date)
public void setTimeInMillis(long millis)
public void set(int field, int value)
public final void set(int year, int month, int date)
public final void set(int year, int month, int date, int hourOfDay, int minute)
public final void set(int year, int month, int date, int hourOfDay, int minute,int second)
Copy the code
Comparison of two Calendar objects: You can refer to the previous two Date objects for comparison, and I won’t go into details here:
In fact, we said in front of Date and Calendar are very familiar with the class, with the most, but because of the use of unfriendly, so after Java8, are using the new ·Instant and Localxxxx series to replace Date and Calendar classes.
Instant 1.3:
Many people say that Date is not good enough to use. If I were to ask you to get the current time, and then add 6 hours to that, and find the time, you would find it a little inconvenient.
Date dd1 = new Date();
dd1.setTime(dd1.getTime()+6*60*60*1000);
//'Date has a setHours() method. But it's actually marked as abandoned. '
Copy the code
Let’s look at the use of Instant:
Instant i = Instant.now(); i.toString(); // 2019-09-04T09.44:07.169z Instant i2 = i.plus(6, chronounit.hours); // 2019-09-04T09.44:07.169z Instant i2 = i.plus(6, chronounit.hours); // Add 6 hours i2.tostring (); // 2019-09-04T15:44:07.169z'Duration class comes later ') Instant i3 = i.plus(Duration.ofHours(6)); i3.toString(); // 2019-09-04T15:44:07.169z //'TimeUnit class will talk about that later. ') Instant i4 = i.plusMillis(TimeUnit.HOURS.toMillis(6)); i4.toString(); / / / / the T15:2019-09-04 44:07. 169 z / /'Minus means use the same method as plus'
Copy the code
The correlation comparison method of the two Instant objects is the same as that of Date:
Here’s the until method:
Instant i = Instant.now(); Instant i2 = i.plus(6,ChronoUnit.HOURS); i2.until(i,ChronoUnit.HOURS); //-6 i.until(i2,ChronoUnit.HOURS); / / 6'(i2.until(i,ChronoUnit.HOURS); I2 to i1, which means to go back, of course, by 6 hours, and vice versa.
Copy the code
PS: Instant.now(); The time is 8 hours slower than our current Time zone in China, please note
1.4 LocalXXXXX series
The Local series includes LocalTime, LocalDate, and LocalDateTime
1. LocalDateTime is a complete date (year, month, day, hour, minute, second).
1.4.1 LocalDate:
The basic method is like the brain map above, and the common methods are also available.
Here’s a point:
Calendar starts with 0 months, so if it’s September, you get 8. But localDate.getMonthValue() gets 9. More realistic.
1.4.2 LocalTime:
The LocalTime method is also included in the brain map above, and common methods are also available.
1.4.3 LocalDateTime:
LocalDateTime = LocalDate + LocalTime
The localdate.attime () method also returns a LocalDateTime object when adding a dateCopy the code
The use of LocalDateTime is basically the same as that of LocalTime and LocalDate.
1.4.4 ZoneDateTime:
LocalDateTime = LocalDateTime = LocalDateTime = LocalDateTime
LocalDateTime.now(); / / T22:2019-09-05 49:06. 369 ZoneDateTime. Now (); / / T22:2019-09-05 49:06. 371 + 08:00 Asia/ShanghaiCopy the code
We can see the current time zone, and the other methods are pretty much the same.
2. Time formatting
We’ve already talked about how to get time. Next we’ll look at various interconversions of time and strings of various formats.
-
But we know that the interface we want to display text is different: 2018-08-07 09:12:12,2018#08#07#09#12#12 various ways, this is the time into a string display.
-
Then suppose someone sends you 2018-08-07 09:12:12, 2018#08#07#09#12#12, and wants to convert the string into a time object.
2.1 the DateFormat:
DateFormat is an abstract class of a date/time formatting subclass that formats and parses dates or times in a language-independent manner. Date/time formatting subclasses (such as SimpleDateFormat) allow formatting (that is, date -> text), parsing (text -> date), and standardization. Represents a Date as a Date object, or as the number of milliseconds starting at 00:00:00 GMT, January 1, 1970.
2.1.1 Time and String Transfer:
DateFormat helps format and parse dates in any locale. For month, week, and even calendar formats (lunar and solar), the code can be completely independent of locale conventions.
To format a date in the current locale, use one of the static factory methods:
myString = DateFormat.getDateInstance().format(myDate);
Copy the code
If you format multiple dates, it is more efficient to take the format and use it multiple times so that the system does not have to retrieve information about the environment language and country/locale conventions multiple times.
DateFormat df = DateFormat.getDateInstance();
for (int i = 0; i < myDate.length; ++i) {
output.println(df.format(myDate[i]) + "; ");
}
Copy the code
To format dates for different locales, you specify it in a call to getDateInstance().
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
Copy the code
You can also use DateFormat for parsing.
myDate = df.parse(myString);
Copy the code
2.1.2 Obtaining DateFormat Objects:
Use getDateInstance to get the standard date format for the country. Several other static factory methods are also provided. Use getTimeInstance to get the time format for the country. Use getDateTimeInstance to get the date and time format. You can pass different options to these factory methods to control the length of the results (from SHORT to MEDIUM to LONG to FULL). The exact results depend on the locale, but in general:
SHORT is purely numeric, such as 12.13.52 or 3:30pm MEDIUM is LONG, such as Jan 12, 1952 LONG is longer, such as January 12, 1952 or 3:30:32pm FULL is fully specified, Such as Tuesday, April 12, 1952 AD or 3:30:42 PM PST.Copy the code
You can also set the time zone on the format if you wish. If you want to exert more control over formatting or parsing (or give the user more control), you can try to cast the DateFormat obtained from the factory method to SimpleDateFormat. This applies to most countries; Just remember to put it in a try block in case you encounter a special format. You can also step through parts of a string using the form of parsing and formatting methods with ParsePosition and FieldPosition. Align any particular field, or find the selected position of the string on the screen. The sync date format is not synchronous. It is recommended to create a separate format instance for each thread. If multiple threads access a format at the same time, it must maintain external synchronization.
SimpleDateFormat 2.2:
SimpleDateFormat is a subclass of DateFormat, so the basic knowledge of the previous DateFormat introduction is basically the same. I won’t make it clear here.
I think 99.9999 percent of you use this class and know how to use it.
The following code is probably the most used:
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); // Convert the time to the string sdf.format(date); //2019-09-06 21:13:23 String str ="The 2019-09-06 21:13:23"; Date = sdf.parse(STR);Copy the code
The main unfamiliarity is not the use of the method, but the definition of the format is always unclear:
The letter date or time element represents the example G Era identifier Text AD Y Year 1996; 96m Month Month July; Jul; 07 Weeks in w Number 27 weeks in W Number 2 days in D Number 189 days in D Number 10 weeks in F Number 2 days in E Text Tuesday; Tue a Am/ PM tag Text PM H Number of hours in a day (0-23) Number 0 K Number of hours in a day (1-24) Number 24 K Number of hours in a day (0-11) Number 0 H Am/ PM Number minutes in 12 m hours Number seconds in 30 s minutes Number 55 s milliseconds Number 978 Z Time zone General time Zone Pacific Standard Time; PST; Gmt-08:00 Z Time zone RFC 822 Time zone-0800Copy the code
2.3 DateTimeFormatter:
This is the recommended conversion class after Java8.
2.3.1 String conversion time object:
// Define an arbitrarily formatted date and time String String str1 ="2014==04==12 01 06:09"; / / the date and time according to the need to parse the string definition format used in the analytical apparatus DateTimeFormatter fomatter1 = DateTimeFormatter. OfPattern ("Yyyy ==MM== DD HH MM minute ss second"); Dt1 = localDatetime. parse(str1, fomatter1); // -- parses another String -- String str2 ="2014? $in April?$1320 hours";
DateTimeFormatter fomatter2 = DateTimeFormatter.ofPattern("yyy?$MMM?$ddHH hours");
LocalDateTime dt2 = LocalDateTime.parse(str2, fomatter2);
Copy the code
The usage here is basically the same as SimpleDateFormat.
2.3.2: Time object conversion string:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("Yyyy ==MM== DD HH MM minute ss second");
//'1. Pass the time object as an argument, just as SimpleDateFormat does. '
formatter.format(LocalDateTime.now());
//'2. Pass the DateTimeFormatter as a parameter '
LocalDateTime.now().format(formatter);
Copy the code
3. Time management
3.1 Comparison Time:
We can see objects that get a direct difference between two dates, mainly the Period class for year, month and day, and the Duration class for seconds.
3.2 Time auxiliary:
3.2.1 TimeUnit:
Time granularity conversion:
Let’s say I want to count N hours M minutes in seconds, and many people might write it that way
N* 60 * 60 + M * 60;
Copy the code
The TimeUnit class makes it easy to convert many different time units.
TimeUnit.HOURS.toSeconds(N) + TimeUnit.MINUTES.toSeconds(M);
Copy the code
Especially for other milliseconds and so on, using ordinary multiplication, so many zeros can easily be mistaken, using TimeUnit is convenient:
TimeUnit.HOURS.toMillis(N) + TimeUnit.MINUTES.toMillis(M);
Copy the code
Timeunit.hours. convert(3, timeunit.days); // The result is 72Copy the code
Delay:
In addition to this, TimeUnit can also be used for thread Sleep:
Write thread sleep for ordinary people:
Thread.sleep( 5 * 1000 );
Copy the code
Using TimeUnit:
TimeUnit.SECONDS.sleep( 5 );
Copy the code
TimeJoin /timeWait, etc.
Conclusion:
Going back to the original question, we started with the song duration acquisition:
We can also use these built-in time tools (I’ll just name two, but there are others)
String str = "00:03:06";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime = LocalTime.parse(str, formatter);
localTime.toSecondOfDay(); //186 String str1 ="00:00:00";
LocalTime time1 = LocalTime.parse(str1);
String str2 = "00:03:06"; LocalTime time2 = LocalTime.parse(str2); Duration duration = Duration.between(time1,time2); duration.getSeconds(); / / 186Copy the code
Also very lazy not to update the article……… Please point out any mistakes.