Convert default java.util.date format to Timestamp in Java

The default java.util.date format looks something like this: "Mon May 27 11:46:15 IST 2013." How can I convert this to a timestamp and calculate in seconds the difference between the same and current time?

java.util.Date date= new java.util.Date(); Timestamp ts_now = new Timestamp(date.getTime()); 

The code above gives me the current timestamp. However, I did not understand how to find the timestamp of the specified string.

+7
source share
4 answers

You can use the Calendar class to convert 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; } 
+10
source

Best

 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; 
+8
source

you can use

  long startTime = date.getTime() * 1000000;; long estimatedTime = System.nanoTime() - startTime; 

To get time in nano.

Java docs

0
source

You can use DateFormat (java.text. *) To parse the date:

 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") 

You will need to change the locale to match yours (with this you get 10:46:15). Then you can use the same code that you need to convert to a timestamp.

0
source

All Articles