将java.util.date默认格式转换为Java中的Timestamp
java.util.date的默认格式是这样的“Mon May 27 11:46:15 IST 2013”。 如何将其转换为时间戳并以秒计算相同和当前时间之间的差异?
java.util.Date date= new java.util.Date(); Timestamp ts_now = new Timestamp(date.getTime());
上面的代码给出了当前的时间戳。 但是,我不知道如何找到上述字符串的时间戳。
您可以使用Calendar
类转换Date
public long getDifference() { SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy"); Date d = sdf.parse("Mon May 27 11:46:15 IST 2013"); Calendar c = Calendar.getInstance(); c.setTime(d); long time = c.getTimeInMillis(); long curr = System.currentTimeMillis(); long diff = curr - time; //Time difference in milliseconds return diff/1000; }
最好的
String str_date=month+"-"+day+"-"+yr; DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); Date date = (Date)formatter.parse(str_date); long output=date.getTime()/1000L; String str=Long.toString(output); long timestamp = Long.parseLong(str) * 1000;
您可以使用
long startTime = date.getTime() * 1000000;; long estimatedTime = System.nanoTime() - startTime;
获得纳米时间。
Java Docs
您可以使用DateFormat
(java.text。*)来解析日期:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH); Date d = df.parse("Mon May 27 11:46:15 IST 2013")
您将不得不更改区域设置以匹配您自己的(使用此function,您将获得10:46:15)。 然后,您可以使用相同的代码将其转换为时间戳。