Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The default format of java.util.date is something like this "Mon May 27 11:46:15 IST 2013". How can I convert this into 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 above code gives me the current timestamp. However, I got no clue how to find the timestamp of the above string.

like image 696
swateek Avatar asked May 27 '13 16:05

swateek


People also ask

Can we convert date to timestamp?

We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).

What is the default format of Java Util date?

The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.

Does Java Util date have time?

No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util.


2 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;
}
like image 134
Rahul Bobhate Avatar answered Nov 15 '22 20:11

Rahul Bobhate


Best one

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;
like image 44
Kishore Avatar answered Nov 15 '22 21:11

Kishore