时间 & 时间戳 之间 转换

o、当前时间

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())
// 当前时间
Date date = new Date();
SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
rq2 = format.format(date);
// 3个月前的今天
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 3);
date = cal.getTime();
rq1 = format.format(date);
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH )+1;
int day = cal.get(Calendar.DAY_OF_MONTH );  

I、当前时间戳

Calendar.getInstance().getTimeInMillis();

js 字符串转时间

var startTime = new Date(Date.parse(rq1.replace(/-/g,   "/"))).getTime();     
var endTime = new Date(Date.parse(rq2.replace(/-/g,   "/"))).getTime();     
var dates = Math.abs((startTime - endTime))/(1000*60*60*24);

java 字符串转时间  

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
  Date date1 = simpleDateFormat.parse(rq1);
} catch (ParseException e) {
  e.printStackTrace();
}

  

一、时间转换成时间戳

try {
  DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      // 当前日期
      // Date date = df.parse(df.format(new Date()));
  Date date = df.parse("2017-06-21 17:14:31");
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  long timestamp = cal.getTimeInMillis();
  System.out.println(timestamp);
} catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}  

二、时间戳转换为时间

try {
  SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Long time = new Long("1498036471000");
  String d = format.format(time);
  Date date1 = format.parse(d);
  System.out.println("Format To String(Date):"+d);
  System.out.println("Format To Date:"+date1);
} catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
posted @ 2017-06-21 17:45  ☀Beans✡✌  阅读(247)  评论(0编辑  收藏  举报