首页 > 代码库 > Java常用代码总结

Java常用代码总结

原创作品,可以转载,但是请标注出处地址: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常用代码总结