JavaSE常用API

1.  Math.round(11.5)于多少?Math.round(-  11.5) 于多?

Math.round(11.5)的返值是  12Math.round(-11.5)回值是-11。四舍五入的原理是在参数上加  0.5然后进行取整。 

2.  switch 能作 byte 上,是作用在 long 是否能用在 String?

Java5switch(expr)expr   byteshortcharint  Java 5 开始Java 了枚举类expr   enum  

Java 7 expr 可以String,但是长整型(long)在目前所有的版本中都是不可以的。 

3.  数组有没length() Stringlength() 

数组 length()法, length String  length()JavaScript 符串的长是通过  length ,这  Java  

4.  String StringBuilder StringBuffer的区

Java的字StringStringBuffer/StringBuilder它们符串别如下 

1String就意String符串。初误解 

1. String str = abc 

2. str = bcd;

str是可以改str指向abc第二行是让 str 重新串“bcdabc”对只不对象已经成 

2StringBuffer/StringBuilder可以 

3StringBuilderJava5中引它和  StringBuffer相同在于线使用,因为synchronized因此StringBuffer 

5.  什么情+运算符行字连接比  StringBuffer/StringBuilder 对象append法连接符串性能更好

 

字符Java用的JavaString"+"。也串可以直接使用"+"代码 

1String s = "abc" + "ddd"; 

但这样做的好?当,这个问不能单地 yes  or  no。要根体情况来。在 Java 提供了StringBuilder个类J2SE5使StringBuffer类也可以"+"作用个呢 

下面代码 

1. package string;

2.  

3.   public class TestSimplePlus

4.   {

5.       public static void main(String[] args)

6.       {

7.           String s = "abc";

8.           String ss = "ok" + s + "xyz" + 5;

9.           System.out.println(ss);

10.       }

11.   } 

上面的结字符使"+"号并没有区别的如吗?

下面码的 

我们使jdkjavapjadTestSimplePlus反编Java Byte Code,其的奥

秘就使jad来反,命令如下: 

jad -o -a -s d.java TestSimplePlus.class

反编 

1. package string;

2.  

3. import java.io.PrintStream;

4.  

5. public class TestSimplePlus

6. {

7.     public TestSimplePlus()

8.     {

9.     //    0    0:aload_0

10.     //    1    1:invokespecial   #8   

11.     //    2    4:return

12.     }

13.  

14.     public static void main(String args[])

15.     {

16.       String s = "abc";

17.     //    0    0:ldc1            #16  

18.     //    1    2:astore_1

19.       String ss = (new StringBuilder("ok")).append(s).append("xyz").append(5).toString();

20.     //    2    3:new             #18  

21.     //    3    6:dup

22.     //    4    7:ldc1            #20  

23.     //    5    9:invokespecial   #22  

24.     //    6   12:aload_1

25.     //    7   13:invokevirtual   #25  

26.     //    8   16:ldc1            #29  

27.     //    9   18:invokevirtual   #25  

28.     //   10   21:iconst_5

29.     //   11   22:invokevirtual   #31  

30.     //   12   25:invokevirtual   #34  

31.     //   13   28:astore_2

32.       System.out.println(ss);

33.     //   14   29:getstatic       #38  

34.     //   15   32:aload_2

35.     //   16   33:invokevirtual   #44  

36.     //   17   36:return

37.     }

38. }

读者Java字节家不目的并不Java Byte Code

并不的含义。 

使用 jad 处之一就码和行对码很容易

,虽使"+"然将"+"转换StringBuilder 因此出结Java

无论使用何种方式符串连接,实际上使StringBuilder 

那么结论使"+"StringBuilder的呢?这如果

从运那么"+"StringBuilder是完全等效率那它

大的 

 表达顺序"+"StringBuilder如果

结构使环来生的 Java  Byte  Code 会有们看下的

 

1. package string;

2.  

3.   import java.util.*;

4.  

5.   public class TestComplexPlus

6.   {

7.       public static void main(String[] args)

8.       {

9.           String s = "";

10.           Random rand = new Random();

11.           for (int i = 0; i < 10; i++)

12.           {

13.               s = s + rand.nextInt(1000) + " ";

14.           }

15.           System.out.println(s);

16.       }

17.   }

  Java Byte Code 

1. package string;

2.  

3. import java.io.PrintStream;

4. import java.util.Random;

5.  

6. public class TestComplexPlus

7. { 

8.  

9.     public TestComplexPlus()

10.     {

11.     //    0    0:aload_0

12.     //    1    1:invokespecial   #8   

13.     //    2    4:return

14.     }

15.  

16.     public static void main(String args[])

17.     {

18.         String s = "";

19.     //    0    0:ldc1            #16  

20.     //    1    2:astore_1

21.         Random rand = new Random();

22.     //    2    3:new             #18  

23.     //    3    6:dup

24.     //    4    7:invokespecial   #20  

25.     //    5   10:astore_2

26.         for(int i = 0; i < 10; i++)

27.     //*   6   11:iconst_0

28.     //*   7   12:istore_3

29.     //*   8   13:goto            49

30.          s = (new StringBuilder(String.valueOf(s))).append(rand.nextInt(1000)).append(" ").t oString();

31.     //    9   16:new             #21  

32.     //   10   19:dup

33.     //   11   20:aload_1

34.     //   12   21:invokestatic    #23  

35.     //   13   24:invokespecial   #29  

36.     //   14   27:aload_2

37.     //   15   28:sipush          1000

38.     //   16   31:invokevirtual   #32  

39.     //   17   34:invokevirtual   #36  

40.     //   18   37:ldc1            #40  

41.     //   19   39:invokevirtual   #42  

42.     //   20   42:invokevirtual   #45  

43.     //   21   45:astore_1

44.  

45.     //   22   46:iinc            3  1

46.     //   23   49:iload_3

47.     //   24   50:bipush          10

48.     //   25   52:icmplt          16

49.         System.out.println(s);

50.     //   26   55:getstatic       #49  

51.     //   27   58:aload_1

52.     //   28   59:invokevirtual   #55  

53.     //   29   62:return

54.     }

55. }

  编译"+"StringBuilderStringBuilderfor

部。次循StringBuilder例来10StringBuilder

对象Java回收工作不断么仍

大量题的使StringBuilder来连接字下: 

1. package string;

2.  

3. import java.util.*;

4.  

5. public class TestStringBuilder

6. { 

7.     public static void main(String[] args)

8.     {

9.         String s = "";

10.         Random rand = new Random();

11.         StringBuilder result = new StringBuilder();

12.         for (int i = 0; i < 10; i++)

13.         {

14.             result.append(rand.nextInt(1000));

15.             result.append(" ");

16.         }

17.         System.out.println(result.toString());

18.     }

19. }

上面如下 

1. 20.package string;

2.  

3. import java.io.PrintStream;

4. import java.util.Random;

5.  

6. public class TestStringBuilder

7. { 

8.  

9.     public TestStringBuilder()

10.     {

11.     //    0    0:aload_0

12.     //    1    1:invokespecial   #8   

13.     //    2    4:return

14.     }

15.  

16.     public static void main(String args[])

17.     {

18.         String s = "";

19.     //    0    0:ldc1            #16  

20.     //    1    2:astore_1

21.         Random rand = new Random();

22.     //    2    3:new             #18  

23.     //    3    6:dup

24.     //    4    7:invokespecial   #20  

25.     //    5   10:astore_2

26.         StringBuilder result = new StringBuilder();

27.     //    6   11:new             #21  

28.     //    7   14:dup

29.     //    8   15:invokespecial   #23  

30.     //    9   18:astore_3

31.         for(int i = 0; i < 10; i++)

32.     //*  10   19:iconst_0

33.     //*  11   20:istore          4

34.     //*  12   22:goto            47

35.         {

36.             result.append(rand.nextInt(1000));

37.     //   13   25:aload_3

38.     //   14   26:aload_2

39.     //   15   27:sipush          1000

40.     //   16   30:invokevirtual   #24  

41.     //   17   33:invokevirtual   #28  

42.     //   18   36:pop

43.             result.append(" ");

44.     //   19   37:aload_3

45.     //   20   38:ldc1            #32  

46.     //   21   40:invokevirtual   #34  

47.     //   22   43:pop

48.         }

49.  

50.     //   23   44:iinc            4  1

51.     //   24   47:iload           4

52.     //   25   49:bipush          10

53.     //   26   51:icmplt          25

54.         System.out.println(result.toString());

55.     //   27   54:getstatic       #37  

56.     //   28   57:aload_3

57.     //   29   58:invokevirtual   #43  

58.     //   30   61:invokevirtual   #47  

59.     //   31   64:return

60.     }

61. }

从上看出,创建StringBuilder的代码被放在了for语句外。虽然这样处理在源程序中看起

来复杂,但却换来了更高的效率,同时消耗的资源也更少了。 

使StringBuilder注意不要"+"StringBuilder否则会创StringBuilder

象, 

for (int i = 0; i < 10; i++)

 {

 result.append(rand.nextInt(1000)); 

 result.append(" ");

 }

改成 

for (int i = 0; i < 10; i++

{

 result.append(rand.nextInt(1000) + " ");

}

则反 

 for(int i = 0; i < 10; i++)

 //*  10   19:iconst_0         

 //*  11   20:istore          4

 //*  12   22:goto            65

 {
 result.append((new StringBuilder(String.valueOf(rand.nextInt(1000)))).append(" ").toString());  //   13   25:aload_3          

 //   14   26:new             #21  

 //   15   29:dup              

从上,Java编译器将"+"编译成了StringBuilder,这样for语句每循环一次,又创建了一个

StringBuilder对象。 

 JDK1.4StringBuilderStringBufferJDK1.4"+"

StringBufferJDK1.4StringBuilderStringBufferStringBuilder的功一样只是

StringBuffer线StringBuilder不是线程StringBuilder 

6.  请说出面程序的输出

1. class StringEqualTest { 

2.    public static void main(String[] args) {

3.         String s1 = "Programming";

4.         String s2 = new String("Programming");

5.         String s3 = "Program";

6.         String s4 = "ming"; 

7.         String s5 = "Program" + "ming";

8.         String s6 = s3 + s4;

9.         System.out.println(s1 == s2);               //false 

10.        System.out.println(s1 == s5);               //true 

11.        System.out.println(s1 == s6);              //false 

12.        System.out.println(s1 == s6.intern());   //true 

13.       System.out.println(s2 == s2.intern());    //false 

14.  } 

15. }    

补充需要知识点 

1. String对象的intern()方法会得到字符串对象在常量池中对应的版本的引用(如果常量池中有一个字符串与 

String 对象的  equals结果是  true),如果常量池中没有对应的字符串,则该字符串将被添加到常量池中,然后返

回常量池中字符串的引用; 

2. 字符串的+操作其本质是创建了StringBuilder 对象进行  append 操作,然后  StringBuilder 

象用  toString 理成  String 可以  javap -c StringEqualTest.class   class 

  JVM 以看 

7.  Java中的期和

7.1如何取得年月日、小分钟秒?

1. public class DateTimeTest { 

2.  public static void main(String[] args) {

3.    Calendar cal = Calendar.getInstance();

4.    System.out.println(cal.get(Calendar.YEAR));

5.    System.out.println(cal.get(Calendar.MONTH)); // 0 - 11

6.    System.out.println(cal.get(Calendar.DATE));

7.    System.out.println(cal.get(Calendar.HOUR_OF_DAY)); 

8.    System.out.println(cal.get(Calendar.MINUTE)); 

9.    System.out.println(cal.get(Calendar.SECOND)); 

10.    // Java 8 

11.    LocalDateTime dt = LocalDateTime.now();

12.    System.out.println(dt.getYear());

13.    System.out.println(dt.getMonthValue()); // 1 - 12

14.    System.out.println(dt.getDayOfMonth());

15.    System.out.println(dt.getHour());

16.    System.out.println(dt.getMinute());

17.    System.out.println(dt.getSecond());

18.  } 

19. }

7.2如何取得197011000 秒到在的毫秒数

1. Calendar.getInstance().getTimeInMillis();  //第一种方式 

2. System.currentTimeMillis();  //第二种方 

3. // Java 8 

4. Clock.systemDefaultZone().millis();

7.3如何取得某月的最后一天?

1. //获取当前月第一天: 

2. Calendar c = Calendar.getInstance();

3. c.add(Calendar.MONTH, 0); 

4. c.set(Calendar.DAY_OF_MONTH,1);//设置1,当前日期既为本月第一 

5. String first = format.format(c.getTime()); 

6. System.out.println("===============first:"+first); 

7.  

8.   //获取当前月最后一天 

9.  Calendar ca = Calendar.getInstance();

10. ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));

11. String last = format.format(ca.getTime());

12. System.out.println("===============last:"+last);

13.  

14. //Java 8

15. LocalDate today = LocalDate.now();

16. //本月的第一天 

17. LocalDate firstday = LocalDate.of(today.getYear(),today.getMonth(),1);

18. //本月的最后一天 

19. LocalDate lastDay =today.with(TemporalAdjusters.lastDayOfMonth());

20. System.out.println("本月的第一天"+firstday);

21. System.out.println("本月的最后一天"+lastDay);

7.4如何格式化日期?

1Java.text.DataFormat   SimpleDateFormat   format(Date) 

2Java 8   java.time.format.DateTimeFormatter期, 

1. import java.text.SimpleDateFormat; 

2. import java.time.LocalDate; 

3. import java.time.format.DateTimeFormatter; 

4. import java.util.Date; 

5. class DateFormatTest {

6.  

7.     public static void main(String[] args) {

8.        SimpleDateFormat oldFormatter = new SimpleDateFormat("yyyy/MM/dd"); 

9.        Date date1 = new Date(); 

10.        System.out.println(oldFormatter.format(date1)); 

11.  

12.        // Java 8 

13.        DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); 

14.        LocalDate date2 = LocalDate.now(); 

15.        System.out.println(date2.format(newFormatter)); 

16.     } 

17. }

JavaAPI的东西Java 8API

其中  LocalDateLocalTimeLocalDateTimeClockInstant 这些使不变

此是线 

7.5打印昨天的当前时刻 

1. import java.util.Calendar; 

2. class YesterdayCurrent { 

3.    public static void main(String[] args){

4.     Calendar cal = Calendar.getInstance();

5.     cal.add(Calendar.DATE, -1);

6.     System.out.println(cal.getTime());

7.    } 

8. } 

9.  

10.  

11. //java-8

12. import java.time.LocalDateTime;

13. class YesterdayCurrent {

14.    public static void main(String[] args) {

15.       LocalDateTime today = LocalDateTime.now();

16.       LocalDateTime yesterday = today.minusDays(1);

17.       System.out.println(yesterday);

18.    } 

19. }

7.6 Java8的日特性 

Java 8日期/时间 

Java 8/APIJSR-310实现目标实现/

API 

l  不变/API不可变的线好处 

l  关注API人可unix timestamp明确Date时间

TimeDateTime戳(unix timestamp义了 

l  清晰在所方法都被同的到当以使now()

中都format()parse()方法那样专门有一好的理问

题,使厂模你使法,不困难。 

l  实用/API一系列方格式

/,等等。 

l  可扩/APIISO-8601日历可以ISO日历 

Java 8日期/API包解 

l  java.timeJava/API类都是这部分LocalDate,  LocalTime, LocalDateTime, Instant, Period, Duration是不线 数情效地 

l  java.time.chrono :这个包 ISO 定义 API我们 AbstractChronology 类来 

l  java.time.format 个包包能够式化和解析日期间对的类,在绝大多情况,我应该直使 用它java.time包中格式 

l  java.time.temporal这个我们/期或间, 比如第一以非具有“withXXX”的  

l  java.time.zone这个包包相关 

Java 8日期/时间API 

1.java.time.LocalDate 

LocalDate格式(yyyy-MM-dd)可以使now()方法得到当前时间也可份和建一个 LocalDate该类为 now()方法重载们可以ZoneId获得指定日期类提java.sql.Date同的功能使该类我们简单子。 

package com.journaldev.java8.time; 

import java.time.LocalDate; 

import java.time.Month;

import java.time.ZoneId;

/**

 * LocalDate Examples

 * @author pankaj

 *

 */

public class LocalDateExample { 

 public static void main(String[] args) { 

 //Current Date 

 LocalDate today = LocalDate.now(); 

 System.out.println("Current Date="+today); 

 //Creating LocalDate by providing input arguments
 LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1);  System.out.println("Specific Date="+firstDay_2014); 

 //Try creating date by providing invalid inputs 
 //LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);  //Exception in thread "main" java.time.DateTimeException:  

 //Invalid date 'February 29' as '2014' is not a leap year 

 //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc  LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));  System.out.println("Current Date in IST="+todayKolkata); 

 //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST  //LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));

 //Getting date from the base date i.e 01/01/1970 

 LocalDate dateFromBase = LocalDate.ofEpochDay(365); 
 System.out.println("365th day from base date= "+dateFromBase); 

 LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100);

 System.out.println("100th day of 2014="+hundredDay2014); 

 } 

}

输出: 

Current Date=2014-04-28

Specific Date=2014-01-01

Current Date in IST=2014-04-29

365th day from base date= 1971-01-01

100th day of 2014=2014-04-10

2.java.time.LocalTime 

LocalTime 符合,默格式 hh:mm:ss.zzzLocalDate提供可以等输们来的程序使 

package com.journaldev.java8.time; 

import java.time.LocalTime; 

import java.time.ZoneId;

/**

 * LocalTime Examples

 */

public class LocalTimeExample { 

 public static void main(String[] args) { 

 //Current Time 

 LocalTime time = LocalTime.now(); 

 System.out.println("Current Time="+time); 

 //Creating LocalTime by providing input arguments

 LocalTime specificTime = LocalTime.of(12,20,25,40); 

 System.out.println("Specific Time of Day="+specificTime); 

 //Try creating time by providing invalid inputs 

 //LocalTime invalidTime = LocalTime.of(25,20);

 //Exception in thread "main" java.time.DateTimeException:  

 //Invalid value for HourOfDay (valid values 0 - 23): 25

 //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc  LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));  System.out.println("Current Time in IST="+timeKolkata); 

 //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST  //LocalTime todayIST = LocalTime.now(ZoneId.of("IST")); 

 //Getting date from the base date i.e 01/01/1970 

 LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);  System.out.println("10000th second time= "+specificSecondTime); 

 } 

}

输出: 

Current Time=15:51:45.240

Specific Time of Day=12:20:25.000000040 

Current Time in IST=04:21:45.276 

10000th second time= 02:46:40 

3. java.time.LocalDateTime 

LocalDateTime 是一个可变的日-对象,表示一组日-间,默格式 yyyy-MM-dd-HH-mm-

ss.zzz工厂LocalDateLocalTime参数LocalDateTime我们

简单子。 

package com.journaldev.java8.time; 

import java.time.LocalDate; 

import java.time.LocalDateTime; 

import java.time.LocalTime; 

import java.time.Month;

import java.time.ZoneId;

import java.time.ZoneOffset; 

public class LocalDateTimeExample { 

 public static void main(String[] args) { 

 //Current Date 

 LocalDateTime today = LocalDateTime.now(); 

 System.out.println("Current DateTime="+today); 

 //Current Date using LocalDate and LocalTime 
 today = LocalDateTime.of(LocalDate.now(), LocalTime.now());  System.out.println("Current DateTime="+today); 

 //Creating LocalDateTime by providing input arguments 
 LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);

 System.out.println("Specific Date="+specificDate); 

 //Try creating date by providing invalid inputs 
 //LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1);  //Exception in thread "main" java.time.DateTimeException:  

 //Invalid value for HourOfDay (valid values 0 - 23): 25

 //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc  LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));  System.out.println("Current Date in IST="+todayKolkata); 

 //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST  //LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST")); 

 //Getting date from the base date i.e 01/01/1970
 LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);   System.out.println("10000th second time from 01/01/1970= "+dateFromBase); 
 } 

}

输出: 

Current DateTime=2014-04-28T16:00:49.455 

Current DateTime=2014-04-28T16:00:49.493 

Specific Date=2014-01-01T10:10:30 

Current Date in IST=2014-04-29T04:30:49.493

10000th second time from 01/01/1970= 1970-01-01T02:46:40

子中,果我们参数去创建日/间,么系

java.time.DateTimeException常,捕获它。 

同时ZoneId日期/时间数据JavadocZoneid的列

表,以得 

4. java.time.Instant 

Instant的时Unix时间的程 

package com.journaldev.java8.time; 

import java.time.Duration; 

import java.time.Instant;

public class InstantExample { 

 public static void main(String[] args) { 

 //Current timestamp 

 Instant timestamp = Instant.now(); 

 System.out.println("Current Timestamp = "+timestamp); 

 //Instant from timestamp 
 Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());  System.out.println("Specific Time = "+specificTime); 

 //Duration example

 Duration thirtyDay = Duration.ofDays(30); 

 System.out.println(thirtyDay); 

 } 

}

输出: 

Current Timestamp = 2014-04-28T23:20:08.489Z

Specific Time = 2014-04-28T23:20:08.489Z 

PT720H

5. API 

我们多数日期/API现了/周数

还有使TemporalAdjuster调整期间 

package com.journaldev.java8.time; 

import java.time.LocalDate; 

import java.time.LocalTime; 

import java.time.Period;

import java.time.temporal.TemporalAdjusters; 

public class DateAPIUtilities { 

 public static void main(String[] args) { 

 LocalDate today = LocalDate.now(); 

 //Get the Year, check if it's leap year 
 System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear()); 

 //Compare two LocalDate for before and after 
 System.out.println("Today is before 01/01/2015? "+today.isBefore(LocalDate.of(2015,1,1)));

 //Create LocalDateTime from LocalDate 
 System.out.println("Current Time="+today.atTime(LocalTime.now())); 

 //plus and minus operations 
 System.out.println("10 days after today will be "+today.plusDays(10));  System.out.println("3 weeks after today will be "+today.plusWeeks(3));  System.out.println("20 months after today will be "+today.plusMonths(20)); 

 System.out.println("10 days before today will be "+today.minusDays(10));  System.out.println("3 weeks before today will be "+today.minusWeeks(3));  System.out.println("20 months before today will be "+today.minusMonths(20)); 

 //Temporal adjusters for adjusting the dates 

System.out.println("First date of this month= "+today.

with(TemporalAdjusters.firstDayOfMonth())); 
 LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());  System.out.println("Last date of this year= "+lastDayOfYear); 

 Period period = today.until(lastDayOfYear); 

 System.out.println("Period Format= "+period); 
 System.out.println("Months remaining in the year= "+period.getMonths());          } 

}

输出: 

Year 2014 is Leap Year? false 

Today is before 01/01/2015? true 

Current Time=2014-04-28T16:23:53.154 

10 days after today will be 2014-05-08

3 weeks after today will be 2014-05-19

20 months after today will be 2015-12-28

10 days before today will be 2014-04-18

3 weeks before today will be 2014-04-07

20 months before today will be 2012-08-28

First date of this month= 2014-04-01

Last date of this year= 2014-12-31

Period Format= P8M3D

Months remaining in the year= 8 

6.  

将一同的格式析一个字符串见的我们看一

下简 

package com.journaldev.java8.time; 

import java.time.Instant;

import java.time.LocalDate; 

import java.time.LocalDateTime; 

import java.time.format.DateTimeFormatter; 

public class DateParseFormatExample { 

 public static void main(String[] args) { 

 //Format examples

 LocalDate date = LocalDate.now(); 

 //default format

 System.out.println("Default format of LocalDate="+date); 

 //specific format
 System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));  System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

 LocalDateTime dateTime = LocalDateTime.now(); 

 //default format
 System.out.println("Default format of LocalDateTime="+dateTime); 
 //specific format
 System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));   System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE)); 

 Instant timestamp = Instant.now(); 

 //default format
 System.out.println("Default format of Instant="+timestamp); 

 //Parse examples
 LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48", 

 DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")); 

 System.out.println("Default format after parsing = "+dt); 

 } 

}

输出: 

Default format of LocalDate=2014-04-28

28::Apr::2014

20140428

Default format of LocalDateTime=2014-04-28T16:25:49.341

28::Apr::2014 16::25::49

20140428

Default format of Instant=2014-04-28T23:25:49.342Z

Default format after parsing = 2014-04-27T21:39:48

7. 时间支持 

旧的日期/乎所使须的若干工具

法帮为新们来 

package com.journaldev.java8.time; 

import java.time.Instant;

import java.time.LocalDateTime; 

import java.time.ZoneId;

import java.time.ZonedDateTime; 

import java.util.Calendar; 

import java.util.Date;

import java.util.GregorianCalendar; 

import java.util.TimeZone; 

public class DateAPILegacySupport { 

 public static void main(String[] args) { 

 //Date to Instant

 Instant timestamp = new Date().toInstant(); 
 //Now we can convert Instant to LocalDateTime or other similar classes  LocalDateTime date = LocalDateTime.ofInstant(timestamp,  

 ZoneId.of(ZoneId.SHORT_IDS.get("PST"))); 

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

 //Calendar to Instant 

 Instant time = Calendar.getInstance().toInstant(); 

 System.out.println(time); 

 //TimeZone to ZoneId 

 ZoneId defaultZone = TimeZone.getDefault().toZoneId(); 

 System.out.println(defaultZone); 

 //ZonedDateTime from specific Calendar 
 ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();  System.out.println(gregorianCalendarDateTime); 

 //Date API to Legacy classes 

 Date dt = Date.from(Instant.now()); 

 System.out.println(dt); 

 TimeZone tz = TimeZone.getTimeZone(defaultZone); 

 System.out.println(tz); 

 GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);  System.out.println(gc); 

 } 

}

输出: 

Date = 2014-04-28T16:28:54.340 

2014-04-28T23:28:54.395Z

America/Los_Angeles

2014-04-28T16:28:54.404-07:00[America/Los_Angeles] 

Mon Apr 28 16:28:54 PDT 2014 

sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-
28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=A merica/Los_Angeles,offset=-
28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startD ayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime= 7200000,endTimeMode=0]]
java.util.GregorianCalendar[time=1398727734404,areFieldsSet=true,areAllFieldsSet=true,lenient=t rue,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-
28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=A merica/Los_Angeles,offset=-
28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startD ayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime= 7200000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=3,WEEK_OF_Y EAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=118,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1 ,HOUR=4,HOUR_OF_DAY=16,MINUTE=28,SECOND=54,MILLISECOND=404,ZONE_OFFSET=-28800000,DST_OFFSET=3600000] 

补充TimeZoneGregorianCalendartoString()方法友好 

7.7 Java8之前日期和间使用的槽点  

Tiago  Fernandez 做过一投票选举  JAVA  API排第一的  EJB2.X第二就是  APIDate Calender 

1. 槽点 

最开Date 承载期之同日较繁单一职纯属~哈) 

后来  JDK 1.1 ,这三项 

  1使用  Calendar 类实间转 

  2使用  DateFormat 字符 

  3  Date 承载息。 

  Date 已废  Date  Calendar,都用着便  API 有设计好方。 

2. 槽点 

坑爹 year  month 

我们 

1. Date date = new Date(2012,1,1); 

2. System.out.println(date); 

  Thu Feb 01 00:00:00 CST 3912
观察year   2012+1900  month月份  1 ?怎Feb 应该你要使  java.util.Calendar...

1. Calendar calendar = Calendar.getInstance(); 

2. calendar.set(2013, 8, 2); 

这样calendar   month   0   8   7 干脆用枚 

1. calendar.set(2013, Calendar.AUGUST, 2);

注意Calendar   1900定义  Date 种不致真

是让知道Calendar   API   IBM 所以 

3. 槽点 

java.util.Date   java.util.Calendar 都是 

下面期之.... 

1. public static void main(String[] args) {

2.    Calendar birth = Calendar.getInstance();

3.    birth.set(1975, Calendar.MAY, 26);

4.    Calendar now = Calendar.getInstance();

5.    System.out.println(daysBetween(birth, now));

6.    System.out.println(daysBetween(birth, now)); // 显示 0 

7. } 

8.  

9. public static long daysBetween(Calendar begin, Calendar end) {

10.    long daysBetween = 0; 

11.   while(begin.before(end)) {

12.      begin.add(Calendar.DAY_OF_MONTH, 1);

13.      daysBetween++; 

14.   } 

15.   return daysBetween; 

16. }

daysBetween 连续  Date ,第  0  Calendar 态是变的

虑到好复  Calendar

1. public static long daysBetween(Calendar begin, Calendar end) { 

2.    Calendar calendar = (Calendar) begin.clone(); //  

3.    long daysBetween = 0; 

4.    while(calendar.before(end)) { 

5.       calendar.add(Calendar.DAY_OF_MONTH, 1);

6.       daysBetween++; 

7.    } 

8.    return daysBetween; 

9. } 

以上第三  java 广使用的  JODA-TIME还有  Date4j 方库已3 / 8强大比如  JSF 器与  joda-time API 兼容要编写标准  API 于是  JSR310 

7.8 Java8日期JSR310

1. JSR310 

JSR 310 个日期概  Instant  java.util.Date 表了一个定的时  Java 1970   1   1   java.util.Date 是其了纳秒 

第二观念  LocalDate   LocalTime了一是日(不包含(不  java.sql 外,  MonthDay,它某人)。正确  java.util.Date 用午  12 分日期  1970-01-01 来表间。 

  Java8   JSR310 新增  java.time 表示-的规则,包括  instants,durations, dates, times, time-zones and periods都是基于  ISO 是遵 Gregorian 最重要的线程图,  java.time 些主方便 

2. Java8方法概 

java.time概览 

方法 

 

Of 

静态工 

parse 

静态工方法关注于解 

get 

获取某东西的值 

is 

检查某东西是否是  true

with

不可变的  setter 价物 

plus 

加一些到某 

minus 

从某个象减一些 

to 

转换到一个类型 

at 

把这个象与一个组合起 

API 

3. 简单实java.timeAPI 

1. public class TimeIntroduction { 

2.   public static void testClock() throws InterruptedException {

3.      //时钟提供给我们用访问某个特 时区的 瞬时间、日  时间的 

4.      Clock c1 = Clock.systemUTC(); //系统默认 UTC 时钟(当前瞬时时间 System.currentTimeMillis() 

5.      System.out.println(c1.millis()); //每次调用将返回当前瞬时时间UTC 

6.      Clock c2 = Clock.systemDefaultZone(); //系统默认时区时钟(当前瞬时时间 

7.      Clock c31 = Clock.system(ZoneId.of("Europe/Paris")); //巴黎时区 

8.      System.out.println(c31.millis()); //每次调用将返回当前瞬时时间UTC 

9.      Clock c32 = Clock.system(ZoneId.of("Asia/Shanghai"));//上海时区 

10.     System.out.println(c32.millis());//每次调用将返回当前瞬时时间(UTC 

11.     Clock c4 = Clock.fixed(Instant.now(), ZoneId.of("Asia/Shanghai"));//固定上海时区时钟 

12.     System.out.println(c4.millis());

13.     Thread.sleep(1000); 

14. 

15.     System.out.println(c4.millis()); //不变 时钟时钟在那一个点不 

16.     Clock c5 = Clock.offset(c1, Duration.ofSeconds(2)); //相对于系统默认时钟两秒的时钟 

17.     System.out.println(c1.millis());

18.     System.out.println(c5.millis()); 

19.  } 

20.  public static void testInstant() {

21.       //瞬时时 相当于前的 System.currentTimeMillis()

22.       Instant instant1 = Instant.now();

23.       System.out.println(instant1.getEpochSecond());//精确到秒 得到对于 1970-01-01 00:00:00 

24.  UTC 的一个时 

25.       System.out.println(instant1.toEpochMilli()); //精确到毫秒 

26.       Clock clock1 = Clock.systemUTC(); //获取系统 UTC 默认时 

27.       Instant instant2 = Instant.now(clock1);//得到时钟的瞬时时间 

28.       System.out.println(instant2.toEpochMilli());

29.       Clock clock2 = Clock.fixed(instant1, ZoneId.systemDefault()); //固定瞬时时间时钟 

30.       Instant instant3 = Instant.now(clock2);//得到时钟的瞬时时间 

31.       System.out.println(instant3.toEpochMilli());//equals instant1

32.   } 

33.    public static void testLocalDateTime() {

34.    //使用默认时区时钟瞬时间创建 Clock.systemDefaultZone() -->即相对于 ZoneId.systemDefault()

35. 默认时区 

36.    LocalDateTime now = LocalDateTime.now();

37.    System.out.println(now);

38.    //自定义时 

39.    LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Europe/Paris")); 

40.    System.out.println(now2);//会以相应的时区显示日 

41.     //自定义时 

42.    Clock clock = Clock.system(ZoneId.of("Asia/Dhaka")); 

43.    LocalDateTime now3 = LocalDateTime.now(clock); 

44.    System.out.println(now3);//会以相应的时区显示日 

45.    //不需要写什么相对时间  java.util.Date 年是对于 1900 月是 0  

46.    //2013-12-31 23:59 

47.    LocalDateTime d1 = LocalDateTime.of(2013, 12, 31, 23, 59);

48.    //年月日 时分  

49.    LocalDateTime d2 = LocalDateTime.of(2013, 12, 31, 23, 59, 59, 11); 

50.    //使用瞬时时间 +  

51.    Instant instant = Instant.now();

52.    LocalDateTime d3 = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()); 

53.    System.out.println(d3); 

54.    //解析 String--->LocalDateTime 

55.    LocalDateTime d4 = LocalDateTime.parse("2013-12-31T23:59");

56.    System.out.println(d4); 

57.    LocalDateTime d5 = LocalDateTime.parse("2013-12-31T23:59:59.999");//999 毫秒 等价 

58. 999000000  

59.  

60.    System.out.println(d5); 

61.    //使用 DateTimeFormatter API 解析  格式 

62.    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); 

63.    LocalDateTime d6 = LocalDateTime.parse("2013/12/31 23:59:59", formatter); 

64.    System.out.println(formatter.format(d6));

65.    //时间获 

66.    System.out.println(d6.getYear());

67.    System.out.println(d6.getMonth());

68.    System.out.println(d6.getDayOfYear());

69.    System.out.println(d6.getDayOfMonth());

70.    System.out.println(d6.getDayOfWeek());

71.    System.out.println(d6.getHour());

72.    System.out.println(d6.getMinute());

73.    System.out.println(d6.getSecond());

74.    System.out.println(d6.getNano());

75.    //时间增 

76.    LocalDateTime d7 = d6.minusDays(1);

77.    LocalDateTime d8 = d7.plus(1, IsoFields.QUARTER_YEARS); 

78.    //LocalDate 即年月 无时分 

79.    //LocalTime 即时分 无年月 

80.    //API  LocalDateTime 类似就不演示 

81.    } 

82.    public static void testZonedDateTime() {

83.    //即带有时区的 date-time 存储纳秒、时区和时差避免与本 date-time )。 

84.    //API  LocalDateTime 类似,只是多了时差( 2013-12-20T10:35:50.711+08:00[Asia/Shanghai])

85.    ZonedDateTime now = ZonedDateTime.now();

86.    System.out.println(now);

87.    ZonedDateTime now2 = ZonedDateTime.now(ZoneId.of("Europe/Paris")); 

88.    System.out.println(now2); 

89.    //其他的用法也是类似的 就不介绍了 

90.    ZonedDateTime z1 = ZonedDateTime.parse("2013-12-31T23:59:59Z[Europe/Paris]");

91.    System.out.println(z1); 

92. }

93.    public static void testDuration() {

94.    //表示两个瞬时时间的间段 

95.    Duration d1 = Duration.between(Instant.ofEpochMilli(System.currentTimeMillis() - 12323123), 

96.  Instant.now()) 

97. ;

98.    //得到相应的时 

99.    System.out.println(d1.toDays());

100.    System.out.println(d1.toHours());

101.    System.out.println(d1.toMinutes());

102.  

103.    System.out.println(d1.toMillis());

104.   System.out.println(d1.toNanos());

105.   //1 天时差 类似的还有 ofHours()

106.   Duration d2 = Duration.ofDays(1);

107.   System.out.println(d2.toDays());

108. }

109.   public static void testChronology() {

110.    //提供对 java.util.Calendar 的替换,提供对年系统的支 

111.     Chronology c = HijrahChronology.INSTANCE; 

112.     ChronoLocalDateTime d = c.localDateTime(LocalDateTime.now());

113.     System.out.println(d);

114.   } 

115. /**

116. * 新旧日期转 

117. */

118.  public static void testNewOldDateConversion(){ 

119.   Instant instant=new Date().toInstant();

120.   Date date=Date.from(instant);

121.   System.out.println(instant);

122.   System.out.println(date);

123.  } 

124.  public static void main(String[] args) throws InterruptedException { 

125.   testClock(); 

126.   testInstant(); 

127.   testLocalDateTime(); 

128.   testZonedDateTime(); 

129.   testDuration(); 

130.   testChronology(); 

131.   testNewOldDateConversion();

132.  } 

133. }

7.9 JSR310Joda-Time的区  

  JSR310 领导  Stephen Colebourne,同  Joda-Time 的创JSR310   Joda-

Time 参考  API但并  JSR310=JODA-Time显的是: 

1.   是包名(  org.joda.time   java.time 

2.    JSR310   NULL Joda-Time   NULL   0 

3.    JSR310 关的Instant人类DateTime 

4.    JSR310 异常  DateTimeException   DateTimeException  

RuntimeException 

7.10   (2017-11-23-wl) 

Java.time

java.util.Calendar 以及  Date 

流畅的  API 

不流畅的  API 

实例不 

实例可 

线程安 

非线程安全 

你可能感兴趣的:(java,javascript,servlet)