SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date= sdf.parse("2018-06-05 13:01:25");
System.out.println(date.getTime());
System.out.println(sdf.format(date.getTime()));
这个例子就足以说明Date类型的数据如何转换为Long类型
Long类型的日期如何转换为Date
特别是第三方接口,很多接口传参除了传签名外还有时间戳,时间戳通常就是用Long类型的时间表示的(这里指的是将Date转为Long类型)
之所以做主要考虑到安全。
Date dt =new Date();
System.out.println(dt); //格式: Wed Jul 06 09:28:19 CST 2016
//格式:2018-6-24
String formatDate = null;
formatDate = DateFormat.getDateInstance().format(dt);
System.out.println(formatDate);
//格式:2018年6月24日 星期三
formatDate = DateFormat.getDateInstance(DateFormat.FULL).format(dt);
System.out.println(formatDate);
//格式 24小时制:2018-06-24 09:39:58
DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制;
formatDate = dFormat.format(dt);
System.out.println(formatDate);
//格式12小时制:2018-06-24 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 -> 2018-06-24 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型:2018-06-24 10:17:48 -> Wed Jul 06 10:17:48 CST 2016
String strDate = "2018-06-24 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();
}
以上是比较常用的时间类型转换,通常签名比较常用的就是Long类型的时间戳,支付用的比较多,为了安全起见。
至于String类型的话,什么创建时间,更新时间等比较常用。