Java中String以及Date的各种转换小结,以及Date的使用

====String 转成Int=======

1). int i = Integer.parseInt([String]); 或

i = Integer.parseInt([String],[int radix]);

2). int i = Integer.valueOf(my_str).intValue();

====INT转String=============

有叁种方法:

1.) String s = String.valueOf(i);

2.) String s = Integer.toString(i);

3.) String s = "" + i;

注: Double, Float, Long 转成字串的方法大同小异.

====字符串时间格式转成Date====

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
        String dstr="2008-4-24";
        Date time = sdf.parse(dstr);
        System.out.println(time);//Thu Apr 24 00:00:00 CST 2008

====Date转成字符串时间格式====

SimpleDateFormat   formatter   = new   SimpleDateFormat( "yyyy-MM-dd ");

String date = formatter.format(new Date());

====Date的各种使用============

Date dt =new Date();

System.out.println(dt); //格式: Wed Jul 06 09:28:19 CST 2016

//格式:2016-7-6

String formatDate = null;

formatDate = DateFormat.getDateInstance().format(dt);

System.out.println(formatDate);

//格式:2016年7月6日 星期三

formatDate = DateFormat.getDateInstance(DateFormat.FULL).format(dt);

System.out.println(formatDate);

//格式 24小时制:2016-07-06 09:39:58

DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制;

formatDate = dFormat.format(dt);

System.out.println(formatDate);

//格式12小时制:2016-07-06 09:42:44

DateFormat dFormat12 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //hh表示12小时制;

formatDate = dFormat12.format(dt);

System.out.println(formatDate);

//格式去掉分隔符24小时制:20160706094533

DateFormat dFormat3 = new SimpleDateFormat("yyyyMMddHHmmss");

formatDate = dFormat3.format(dt);

System.out.println(formatDate);

//格式转成long型:1467770970

long lTime = dt.getTime() / 1000;

System.out.println(lTime);

//格式long型转成Date型,再转成String: 1464710394 -> ltime2*1000 -> 2016-05-31 23:59:54

long ltime2 = 1464710394;

SimpleDateFormat lsdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date lDate = new Date(ltime2*1000);

String lStrDate = lsdFormat.format(lDate);

System.out.println(lStrDate);

//格式String型转成Date型:2016-07-06 10:17:48 -> Wed Jul 06 10:17:48 CST 2016

String strDate = "2016-07-06 10:17:48";

SimpleDateFormat lsdStrFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {

Date strD = lsdStrFormat.parse(strDate);

System.out.println(strD);

} catch (ParseException e) {

e.printStackTrace();

}

====计算时间差=============
String beginTime=new String("2014-08-15 10:22:22"); 
String endTime=new String("2014-09-02 11:22:22"); 
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
long bt=sdf.parse(beginTime).getTime(); 
long et=sdf.parse(endTime).getTime(); 
long cha=(et-bt)/(1000*60*60*24);
System.out.println(cha);//18

求点赞、扩散、评论不足、共同进步!!!

猜你喜欢

转载自blog.csdn.net/qq_39693164/article/details/81557337