yatinbc
yatinbc

Reputation: 625

How to convert String timestamp to milliseconds

I am running one query on oracle sql which returns me timestamp part of of sysdate in string something like "16:30:0.0" so i want to know how to convert it to milliseconds.

please help?

Upvotes: 0

Views: 3460

Answers (3)

ovunccetin
ovunccetin

Reputation: 8683

Try this,

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = sdf.parse("16:30:0.0");
System.out.println(date.getTime());

But, this code will return milliseconds since 01.01.1970 16:30:00.000. If you want to get millis from the current day you can do the following.

Calendar today = Calendar.getInstance();

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.YEAR, today.get(Calendar.YEAR));
cal.set(Calendar.MONTH, today.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, today.get(Calendar.DAY_OF_MONTH));

System.out.println(cal.getTimeInMillis());

Upvotes: 0

Durandal
Durandal

Reputation: 20069

Use ResultSet's getTime(column)-method instead of getString(column) to avoid having to do the conversion yourself: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTime%28int%29

Upvotes: 1

Zoltán
Zoltán

Reputation: 22206

This is using the standard Java Date API.

DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse("16:06:43.233").getTime();

If you're using Java 8, see the new java.time API. If not, and you're going to do a lot of date-time-related work, see JodaTime

Upvotes: 2

Related Questions