1. 程式人生 > >Java常用代碼總結

Java常用代碼總結

[] blog http ati target catch () log 字符串格式化

原創作品,可以轉載,但是請標註出處地址:http://www.cnblogs.com/V1haoge/p/7004474.html

1、日期與字符串之間的轉換

 1     public static void main(String[] args) {
 2         Date now = new Date();
 3         String d = "2017-06-13 23:23:23";
 4         
 5         System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
6 try { 7 System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(d)); 8 } catch (ParseException e) { 9 e.printStackTrace(); 10 } 11 }

結果:

2017-06-13 23:31:12
Tue Jun 13 23:23:23 GMT+08:00 2017

2、數值字符串格式化

1     public static void main(String[] args) {
2 Double d = 1234567890.5512d; 3 System.out.println(String.format("%,.2f", d)); 4 }

結果:

1,234,567,890.55

3、日期字符串格式化

 1     public static void main(String[] args) {
 2         Date now = new Date();
 3         System.out.println(String.format("%tc", now));
 4         System.out.println(String.format("%tF", now));
5 System.out.println(String.format("%tD", now)); 6 System.out.println(String.format("%tr", now)); 7 System.out.println(String.format("%tT", now)); 8 System.out.println(String.format("%tR", now)); 9 System.out.println(String.format("%1$tF %2$tT", now,now)); 10 System.out.printf("%tc%n",now); 11 System.out.printf("%tT%n",now); 12 System.out.printf("%1$s %2$tb %2$te,%2$tY%n","date:",now); 13 System.out.printf("%1$tF %2$tT",now,now); 14 }

結果:

星期三 六月 14 01:29:40 GMT+08:00 2017
2017-06-14
06/14/17
01:29:40 上午
01:29:40
01:29
2017-06-14 01:29:40
星期三 六月 14 01:29:40 GMT+08:00 2017
01:29:40
date: 六月 14,2017
2017-06-14 01:29:40

Java常用代碼總結