We are Borg We are Borg - 1 year ago 67
Java Question

Java : Remove seconds from java.sql.Time not working

I am working on a Java application in which I am trying to remove the seconds part of

object before printing it. I tried using
and provide
, but it gives me weird results, which includes the time zone. How can I get String from Time object which doesn't have seconds. I can perform REGEX and simply remove the part after 2nd
, but I was hoping there is something better than that. Thank you.

Code :

SimpleDateFormat sdf = new SimpleDateFormat("HH:MM");
Date formattedDate = sdf.parse(TimeObject.getTargetTime().toString());
String msgToPring= "Message "+formattedDate;

Current output :

Thu Jan 01 14:15:00 IST 1970

I tried a few suggestions on other SO links, but none of them seem to address this.

Answer Source

You are parsing the date (Create a new Date Object from a String), but what you actually have to do is format it (Create a String representation from an existing date):

SimpleDateFormat sdf = new SimpleDateFormat("HH:MM");
String dateString = sdf.format(TimeObject.getTargetTime());
String msgToPring = "Message "+dateString;

Note: This will only create a String representation of your date Object printing out Hours and Seconds. Your original Date object will not change and stil have its full date information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download