Getting the current time using java.sql.Time
I need to set the current time in a database field. I tried the following code (using my logic) to set the current time. But, I end up getting "Jan 1, 1970" in the time field in the database.
Here is the code :
Calendar cal = Calendar.getInstance();
Java.sql.Time now = java.sql.Time.valueOf(
cal.get(Calendar.HOUR_OF_DAY) + ":" +
cal.get(Calendar.MINUTE) + ":" +
cal.get(Calendar.SECOND));
What should I do to get the current time in the "now" variable? Right now, it ends up in the database as "Jan 1, 1970".
Thanx in advance.
Can you show me the code to do SimpleDateFormat?
Assuming that I use the following skeleton to get the
time value from the database, can you show me the
code for the missing link (so as to display in the
format "hh:mm:ss") ?
java.sql.Time timeFromDb =
obj.getActionTime();
// The above code gets the "time" field from
the database into "timeFromDb"
// Use SimpleDateFormat to display the time
java.text.SimpleDateFormat sdf = new
java.text.SimpleDateFormat("hh:mm:ss");
// Now what do I do with "sdf" and
"timeFromDb" ?
// Print out the time value
System.out.printf("Time is : %s\n",
.... );Hi,
I don't know if you want 24h clock or not. This is the pattern for 24h clock.
"HH:mm:ss"
You get the text string by calling sdf.format(timeFromDb)
Kaj
Similar Messages
-
Getting the current time and comparing it to a time in the future
Hello,
I am seeing in my research some debate on the best way to get the time. I am reading that just using the Date class and calling getTime() is not the most reliable way to do things. Overall, I am trying to get the current time down to the millisecond. I then want to add 5 seconds to that time and then store that value. FInally, when the current time is greater or equal to this stored value, I want to continue on in my program. Can anyone point me in the right direction on how to calculate the time variable? Any help would be much appreciated. I am new to the JAVA world.
Thanks,
TimTo store the current time, simply use new java.util.Date(). Yes, there might be slight inconsistencies and it might not be the most accurate time possible, but without significant additional effort (perhaps a native O/S call or the use of another time library), you will not do much better. Calendar won't help in this instance either. The easiest way to get five seconds in the future is to do the following:
Date now = new Date();
Date future = new Date(now.getTime() + 5000);To store and retrieve the value, it depends on what you are doing. You can place it in the database via JDBC (BTW, if you trust the database timestamp more than Java's you can use something like Oracle's SYSDATE instead of Java's date in your SQL query). You can place it in the filesystem. You can store it in the user's session.
- Saish -
Hi I was wondering how I can get the current time and use is to compare it e.g. in a IF sentence.
Hi I was wondering how I can get the current time and
use is to compare it e.g. in a IF sentence.This might help. I'm not exactly sure what you are asking for but I use this type of code to compare the current time to my start time in my program, specifically for my loggerformatter. The output shows the seconds and the remainder in milliseconds. The efficiency is probably suspect, but it might give you some ideas... Joel
import java.util.Date;
import java.text.NumberFormat;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
class TimeDiff {
private static NumberFormat nf08 = NumberFormat.getInstance();
private static GregorianCalendar calStart = new GregorianCalendar();
private static GregorianCalendar calEnd = new GregorianCalendar();
* Constructor
public TimeDiff() {
calStart.setTimeInMillis(System.currentTimeMillis());
* Calculate the elapsed time in seconds
private static long calcSsElapsed(GregorianCalendar calBegin, GregorianCalendar calEnd) {
return((calEnd.getTime().getTime() - calBegin.getTime().getTime()) / 1000);
* Calculate the elasped time milliseconds
private static long calcMsElapsed(GregorianCalendar calBegin, GregorianCalendar calEnd) {
return((calEnd.getTime().getTime() - calBegin.getTime().getTime()) % 1000);
public static void main(String[] args) {
try {
TimeDiff td = new TimeDiff();
Thread.sleep(5100);
calEnd.setTimeInMillis(System.currentTimeMillis());
System.out.println("Seconds="+calcSsElapsed(calStart, calEnd));
System.out.println("Milliseconds="+calcMsElapsed(calStart, calEnd));
catch (Exception e) {
System.out.println("something went terribly, terribly wrong");
} -
Hi All,
I wanted to know if there is anything like getcurrtime() in JAVA to get the current time.
Right now what i am doing is creating a new Date object and then calling getTime() on that new object.
One more question. when you call the getTime() function on an object does it give the time of creating of the object or the current
time.
Thanks in advance,
AmitabhHi All,
I wanted to know if there is anything like
getcurrtime() in JAVA to get the current time.
Right now what i am doing is creating a new Date
object and then calling getTime() on that new object.
One more question. when you call the getTime()
function on an object does it give the time of
creating of the object or the current
time.
Thanks in advance,
AmitabhHola!
You can use
long time = System.currentTimeMillis();
to get the current time in milli seconds (since 1970) :)
If you need a formatted String with the time, you can use:
java.text.DateFormat df = new java.text.SimpleDateFormat("HH:mm:ss"); // "HH:mm:ss", for example
String formattedTime = df.format(new Date());
And when you use the method "getTime()", it returns the Date creation time (because the object is initialized to that time when created)
Hasta pronto! -
Servlet acts as an RMI client to get the current time of day
my application is servlet acts as an RMI client to get the current time of day from the DaytimeServlet RMI server so iam not getting the correctime....
import java.io.*;
import java.rmi.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DaytimeClientServlet extends
HttpServlet
DaytimeServer daytime;
protected DaytimeServer getDaytimeServer() {
DaytimeServer stub.
if (System.getSecurityManager() == null) {
System.setSecurityManager(new
RMISecurityManager());
try {
Registry registry =
LocateRegistry.getRegistry(getRegistryHost(),
getRegistryPort());
return
(DaytimeServer)registry.lookup(getRegistryName());
catch (Exception e) {
getServletContext().log(e, "Problem getting
DaytimeServer reference");
return null;
private String getRegistryName() {
String name = getInitParameter("registryName");
return (name == null ? "DaytimeServlet" : name);
private String getRegistryHost() {
return getInitParameter("registryHost");
private int getRegistryPort() {
try { return
Integer.parseInt(getInitParameter("registryPort");
catch (NumberFormatException e) { return
Registry.REGISTRY_PORT; }
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws
ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (daytime == null) {
daytime = getDaytimeserver();
if (daytime == null) {
throw new UnavailableException(this, "Could
not locate daytime");
out.println(daytime.getDate().toString());
please help me outHi lucentb,
what i observed from your code is some simple coding faults are there.. so i am giving you some test code..
i hope this will help you out.
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DaytimeClientServlet extends HttpServlet
DaytimeServer daytime;
protected DaytimeServer getDaytimeServer()
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
Registry registry = LocateRegistry.getRegistry(getRegistryHost(),
getRegistryPort());
return
(DaytimeServer)registry.lookup(getRegistryName());
catch (Exception e) {
getServletContext().log(e, "Problem getting DaytimeServer reference");
return null;
private String getRegistryName()
String name = getInitParameter("registryName");
return (name == null ? "DaytimeServlet" : name);
private String getRegistryHost() {
return getInitParameter("registryHost");
private int getRegistryPort()
try
return
Integer.parseInt(getInitParameter("registryPort")); }
catch (NumberFormatException e)
return
Registry.REGISTRY_PORT;
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws
ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (daytime == null) {
daytime = getDaytimeServer();
if (daytime == null) {
// Couldn't get it, so report we're
unavailable.
throw new UnavailableException(this, "Could
not locate daytime");
out.println(daytime.getDate().toString());
If you have any problem after this please send me the exceptions and problem situations with deatils codes..
Regards,
TirumalaRao
Developer Technical Support,
Sun Microsystems, India. -
How to get the context data using java script in interactive forms
Hi All,
How to get the context data using java script in interactive forms by adobe, am using web dynpro java
thanks.Hi venkat,
Please Refer this link.
Populating one Drop-Down list from the selection of another Drop-down list
Thanks,
Raju. -
How can I get the current time in Xcelsius?
I'm reading in an XML feed containing dates/times, and I'd like to do a calculation to see how old it is -- but I can't seem to access the current time in Xcelsius (=now() doesn't work -- it only calculates once, when the model is loaded).
I can get around that (a bit awkwardly) with a timer, but I'd also like to know what the user's current time zone is... Any ideas?Hi,
Maybe you could use a web service to return the required information - you can feed the timezone to the web service.
Have a look at this:
http://www.earthtools.org/webservices.htm#timezone
http://markitup.com/WebServices/TimeZones.asmx?op=CurrentDateTime
Best regards,
Jacob -
Get the difference between two java.sql.Time values
Hi, I'm developping a web application in which I need to to subtract one java.sql,Time value from another. The two values are stored in a database field of type DateTime. I used following code
java.sql.Time start_time=resultset.getTime("startTime");
java.sql.Time end_time=resultset.getTime("startTime");
java.sql.Time diff=start_time-end_time;
can u give me any comment on this codeRemember what the Date/Time object in Java represents - a single point in time.
Subtracting one from another gives you an amount of time elapsed between the two dates. Fine.
Making a new Date out of that number is incorrect. The number no longer represents a point in time, but rather a duration.
Its like saying "There is 10 seconds difference between the two times, so the time is now 1 Jan 1970, 00:00:10 GMT".
The simple and stupid calculation is to take the milliseconds difference, and divide it to get to a more humanly readable value.
// duration in milliseconds
long duration = ?????
long durationInSeconds = duration / 1000;
long durationInMinutes = duration / (60 * 1000);
long durationInHours = duration / (60 * 60 * 1000);
// careful - not always true!
long durationInDays = duration / (24 * 60 * 60 * 1000);
NOTE: The "daysBetween" calculation is potentially complicated by Daylight Time adjustments. The simple approach does not necessarily work exactly.
Cheers,
evnafets -
How to get the current filename in java
I want to know that is their any way in java to get the name of the current java file.
In c it is done as
printf("%s",__FILE__);
Thanx in advance.Define "the current file" first. The entire concept is pretty ridiculous in applications that don't work with files, and in most others it's irrelevant because there's never more than one relevant file open that's in use in a particular part of the application so there's no possibility of confusion what file is being worked on at any specific moment.
-
How to get the current date using HTMLB JSP page
Hi All, I developed an iview with several fields using PDK, I would like to know how can I include for a date field a dynamic value witch in this case is the current date.
<hbj:inputField
id="Date"
type="date"
maxlength="10"
showHelp="TRUE"
required="TRUE"
value="???"
/>
Thanks in advance
AlexisHi Alexis ,
u can use the setDate("3.12.2003") function to set date for this input field.
u just change the id = Date , because in jave we have Date class. rename it to another name..
suppose id = systemDate
<%
Format formater = new SimpleDateFormat("dd.MM.yyyy");
Date syDatum = new Date();
%>
then
put
systemDate.setDate(formater.format(syDatum));
this will set the date .....
Regards
Kishor Gopinathan -
How to retrieve the current User using PL_/SQL code?
Hi,
How can find the current logged user within a Dynamic Page using PL/SQL code?
Thanks.Hi,
There is a function wwctx_api.get_user which returns the logged in user. You can use this in your plsql code.
Thanks,
Sharmila -
I am trying to write a heartbeat program which takes the current time and writes
I am trying to write a VI that gets the current time and writes it to an XML file in this format. YYYY-MM-DDThh:mm:ss[.s][Z|(+|-)hh:mm]
I cant seem to get the operators on the format date/time string vi to work for concatenating the "-" between the year and month
Anybody know how to do this one?You should not need to use special operaors for the format date/time string, the format should simply be"%Y-%m-%d"
-
Get the current week and subtract 12 weeks
Hi Experts,
Am getting the system current date and getting the current week using the FM->GET_WEEK_INFO_BASED_ON_DATE. Again I want to subtract 12 weeks including the current week. But still confused with the logic.
Also I came to know that I can use FM->DATE_GET_WEEK and can subtract 12 weeks from it.
So please advice how can I proceed further and how can I get the weeks that should be lesser than the 12weeks from the current week.
Waiting for your valuable ideas.:)
Thanks and Regards,
Ramakrishnan MTry this one:
DATA: week TYPE numc1,
days TYPE t5a4a-dlydy,
date TYPE p0001-begda,
months TYPE t5a4a-dlymo,
years TYPE t5a4a-dlyyr.
CALL FUNCTION 'RP_CALC_DATE_IN_INTERVAL'
EXPORTING
date = s_ord_dt-low
days = days
months = months
signum = '+'
years = years
IMPORTING
calc_date = date. -
How to get the current GMT time in java
Hi,
How to get the current GMT time in java
ThanksSystem.getCurrentTimeMillis() or new Date().
[url http://www.javaworld.com/jw-12-2000/jw-1229-dates.html]Calculating Java dates: Take the time to learn how to create and use dates
[url http://www.javaalmanac.com/egs/java.text/FormatDate.html]Formatting a Date Using a Custom Format -
Java always returns 15 minutes greater than the current time.
Hi,
I am using Microsoft Windows Server 2003R2,Standard X64 edition with Service Pack 2 and jdk1.6.0-03.
Java always returns time 15 minutes greater than the current system time.
eg:
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Now time: "+simpleDateFormat.format(new Date()));
System.out.println("Now time: "+new Date());The output of the program is :
Now time: 2008-12-22 18:47:04
Now time: Mon Dec 22 18:47:04 NPT 2008
When my actual system time is 6:32 PM or (18:32)
I have checked the current time with other programming languages like python and it always returns the actual date and time.
Note: To my observation java is always utilizing a time which is 15 minutes greater than the current time even for its log.
Thanks,
Rajeswari (Msys)I think a more practical time machine would be one that actually travels back in time rather than forward (by 15 minutes). Sounds like it needs some more work.
Anyway, I suggest changing the system time on your computer to some other value (say, 2 hours ahead), then running the program again. If its off by 2 hours and 15 minutes, its getting the time from your computer. However, if its still off by only 15 minutes (from your wristwatch's time), then its getting the time form somehere other than the computer clock.
Maybe you are looking for
-
Adobe Premiere Elements 10 and Photoshop Elements 10
This product worked great up till yesterday. I went to open it and it wouldn't allow me to open it. I uninstalled the program, jumped through all the hoop to re-instal it, and it still doesn't work. Why all of a sudden? I've tried re-booting my compu
-
I am designing query based on dso
Hi, i am designing query based on dso. in my query production orders have multiple operations.when i execute my query report is showing only latest operations.we need to all operation.how can i fetch. ex : production order
-
How to view server .pdf file in WDP
Hi, I want to open/view the file(.pdf) in WebDynpro which is attched in SAP CRM transaction as document. Can anybody help me in this. Regards, Harshad.
-
How do i view my imessages online
I broke my phone this weekend and need to retrive info that is in my imessages for work. Is there a way I can view them online?
-
i have a LG BX327 projector which i'm unable to connect to my macbook pro, i have the HDMI, i have the adaptor but still whenever i connect it gives me an error NO SIGNAL!!!