Get the current time

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

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,
    Tim

    To 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

  • 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

  • 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 out

    Hi 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.

  • To get the current time

    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,
    Amitabh

    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,
    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!

  • 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

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

  • How can I get a digital WDT that includes all samples, not just the one for the current time step...?

    See block labeled ''digital data'' in my attachment for reference. Currently, only the digital data point for the current time step can be seen (it is deleted before the next one appears). However, I would like it display all the samples in the table like in the example found at this link under ''Digital Waveform Control'':
    http://zone.ni.com/reference/en-XX/help/371361H-01/lvconcepts/fp_controls_indicators/ 
    Many thanks for any suggestions! I am new to Labview, so I appreciate your help.
    Solved!
    Go to Solution.
    Attachments:
    myproject.vi ‏220 KB

    Hey westerman111,
    If you're looking to produce have your display include the solution information from previous solver steps, you will need to buffer the previous data. The way to implement this in a Control Design & Simulation Loop is using the Memory.vi found under Control Design & Simulation > Simulation > Utilities > Memory.vi. It will allow you to save previous information generated in the simulation environment for letter solution steps.
    I've attached an example that should get you started in using the Memory.vi.
    I would also make sure that what you're looking to accomplish is suitable for the Control & Simulation Loop. I know you mentioned you were new to LabVIEW so I wanted to make sure you were heading off in the right direction. Is there a particular reason why you are using the Control & Simulation Loop instead of a standard While or For Loop? The Control Design & Simulation loop is unique in that it calculates the solution of a dynamic system at a prescribed time step and ODE solver. It also provides the tools to interact with the model you are solving during execution. However, if you are simply looking to perform data acquisition and measurements (instead of dynamic model simulation) I would recommend using standard LabVIEW functions.
    Here are some useful references for getting start with both LabVIEW and the Control Design and Simulation Module.
    Tutorial: Getting Started with Simulation (Control Design and Simulation Module)
    http://zone.ni.com/reference/en-XX/help/371894G-01/lvsimhowto/sim_h_gs/
    Getting Started with LabVIEW
    http://digital.ni.com/manuals.nsf/websearch/ba2fb433a7940e7a862579d40070cc2c
    Tim A.
    National Instruments
    Attachments:
    myproject_edit.vi ‏249 KB

  • How to get the current GMT time in java

    Hi,
    How to get the current GMT time in java
    Thanks

    System.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

  • I need to get the Current System Date and time in the format

    I need to get the Current System Date and time in the format
    *6/24/2009 11:30:29 AM*
    How do i do it ?

    I seem to be saying this a lot lately.
    Google is your friend.
    I googled "java current date format" and SimpleDateFormat featured prominently in the results.

  • How to get the day value from the current time?

    Hi,
    I like to write a program that prints out the current time in the formate as "Thu May 3 07:57:02 PDT 2002". Then I want to get the day, time, year and month value out and do some manipulation.
    I know to format the current time, I can use
    SimpleDateFormat formatter
    = new SimpleDateFormat ("EEE MM.dd hh:mm:ss z yyyy");
    Date currentTime_1 = new Date();
    Now how do I get the day, time, year and month value? All the getday(), gettime()..,method have been deprecated. Can anyone provide the answer?
    Thanks.

    Try using Calendar.get(int) and take a look at the constants used to specify the field you are trying to access.

  • How cost;ly it is to get the current system time

    I am using this call "System.currentTimeMillis()" to get the current system time. I need to now how costly it is to get the current system time.

    Why don't you time it -:) Run it 10000 times and print the first and last result. The difference is the time it took.

  • Get the Current Date and Time of a Location

    I have created a windowsPhoneApplication in silverLight 8.1.In my application,I have to upload videos on some server.The Uploading get failed If the Date and Time settings of my device is not the current Date and Time.So How can I get the current date
    and time even if the device settings is wrong?

    Hi shifana,
    Do you know server's time zone? If yes, you can manually translate to the correct time zone.
    Otherwise try some online time acquire API.
    --James
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to check the current time with a Stored  time in string format

    Hi All
    I would like to compare the system time with an existing time values which is allready there in String format..
    i mean i would like to check if the SysTime is inbetween 6:30 and 14:00
    I accomplished this in Oracle ..
    Select 'Y' from dual where to_date(to_char(sysdate,'HH24:MI '),'HH24:MI') between to_date('06:30','HH24:MI') and to_date('14:00','HH24:MI')
    But instead of checking the DB each and every time , the perfomance would be better if we can do this in our java code..
    Could some one provide me with a code to accomplish the above scenario..
    Thanks in advance..,.,

    import java.util.Calendar;
    Calendar rightNow = Calendar.getInstance();  // gets the current date and time to millisec
    Calendar earlyTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 6).set(Calendar.MINUTE, 30);
    Calendar lateTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 8).set(Calendar.MINUTE, 0);
    if (rightNow.compareTo(earlyTime)> 0 && rightNow.compareTo(lateTime) < 0){
    // do something
    }Try this.

  • Oracle 11i release 2 error "Unable to get the current group"

    Hi oracle gurus,
         I have been trying to install oracle 11g rel 2 on HPUX 11.31 and i am getting the following error
    # more installActions2010-01-06_10-27-37AM.log
    oracle.install.ivw.db.driver.DBInstaller
    -scratchPath
    /u01/tmp/OraInstall2010-01-06_10-27-37AM
    -sourceLoc
    /u01/install/database/install/../stage/products.xml
    -sourceType
    network
    -timestamp
    2010-01-06_10-27-37AM
    INFO: Loading data from: jar:file:/u01/tmp/OraInstall2010-01-06_10-27-37AM/ext/jlib/installcommons_1.0.0b.jar!/oracle/install/driver/oui/resource/ConfigComma
    ndMappings.xml
    INFO: Loading beanstore from jar:file:/u01/tmp/OraInstall2010-01-06_10-27-37AM/ext/jlib/installcommons_1.0.0b.jar!/oracle/install/driver/oui/resource/ConfigC
    ommandMappings.xml
    INFO: Restoring class oracle.install.driver.oui.ConfigCmdMappings from jar:file:/u01/tmp/OraInstall2010-01-06_10-27-37AM/ext/jlib/installcommons_1.0.0b.jar!/
    oracle/install/driver/oui/resource/ConfigCommandMappings.xml
    SEVERE: [FATAL] An internal error occurred within cluster verification framework
    Unable to get the current group.
    Refer associated stacktrace #oracle.install.commons.util.exception.DefaultErrorAdvisor:11
    INFO: Advice is ABORT
    SEVERE: Unconditional Exit
    INFO: Adding ExitStatus FAILURE to the exit status set
    INFO: Finding the most appropriate exit status for the current application
    INFO: Exit Status is -1
    INFO: Shutdown Oracle Database 11g Release 2 Installer
    $
    >>
    # more oraInstall2010-01-06_10-27-37AM.err
    ---# Begin Stacktrace #---------------------------
    ID: oracle.install.commons.util.exception.DefaultErrorAdvisor:11
    oracle.cluster.verification.VerificationException: An internal error occurred within cluster verification framework
    Unable to get the current group
    at oracle.cluster.verification.ClusterVerification.<init>(ClusterVerification.java:200)
    at oracle.cluster.verification.ClusterVerification.getInstance(ClusterVerification.java:294)
    at oracle.install.driver.oui.OUISetupDriver.load(OUISetupDriver.java:407)
    at oracle.install.ivw.db.driver.DBSetupDriver.load(DBSetupDriver.java:161)
    at oracle.install.commons.base.driver.common.Installer.run(Installer.java:216)
    at oracle.install.ivw.db.driver.DBInstaller.run(DBInstaller.java:126)
    at oracle.install.commons.util.Application.startup(Application.java:869)
    at oracle.install.commons.flow.FlowApplication.startup(FlowApplication.java:164)
    at oracle.install.commons.flow.FlowApplication.startup(FlowApplication.java:181)
    at oracle.install.commons.base.driver.common.Installer.startup(Installer.java:265)
    at oracle.install.ivw.db.driver.DBInstaller.startup(DBInstaller.java:114)
    at oracle.install.ivw.db.driver.DBInstaller.main(DBInstaller.java:132)
    ---# End Stacktrace #-----------------------------
    <<
    $ uname -a
    HP-UX rx2600 B.11.31 U ia64 <XXXXXXXX> unlimited-user license
    # swlist | grep -i oe
    HP-Caliper-PERF C.11.31.04 HP Caliper OE Bundle
    HP-WDB-DEBUGGER C.11.31.04 HP DEBUGGER OE Bundle
    HPUX11i-DC-OE B.11.31.0903 HP-UX Data Center Operating Environment
    # swlist | grep -i qpk
    QPKBASE B.11.31.0903.334a Base Quality Pack Bundle for HP-UX 11i v3, March 2009
    # swlist -l product | grep -i c++
    ACXX C.06.20 HP C/aC++ Compiler
    C-ANSI-C C.06.20 HP C/aC++ Compiler
    PHSS_37501 1.0 aC++ Runtime (IA: A.06.16, PA: A.03.76)
    PHSS_39824 1.0 HP C/aC++ Compiler (A.06.23)
    i start the installation as oracle and my group and user id is
    $ id
    uid=109(oracle) gid=102(oinstall) groups=101(dba),104(asmdba)
    Please let me know what else do i need, we might have to use the hardware for testing another application so i am limited in terms of time constraints
    any help is much appreciated, Thank you!!
    Regards,
    Dasjith
    Edited by: user10247524 on Jan 6, 2010 7:52 AM

    Hi Stig Sundqvist
    Where can i find MOS Doc 983713.1 ??You have to login https://support.oracle.com/CSP/ui/flash.html and you have to CSI account. This site is oracle site for tech. documents for can rise SR etc.. for more details please check
    What is CSI:
    Re: Installing Oracle Database 10.2.0.4
    And how do i do to fix this problem ????Login metalink then find upper note and follow document
    Hope it helps
    Regard
    Helios

Maybe you are looking for

  • Bug with multi-disc albums?

    I've been using iTunes for about 3 years, and I recently bought Stadium Arcadium and ripped it to my computer and added it to my iTunes library. I'm pretty meticulous with my ID tags so I naturally thought to add which disc was which through the iTun

  • Fatal NI connect error 12547/12170

    Hi, I am stakk with connection problem on customer Oracle server. Oracle database is installed on Microsoft Windows Server 2012 Standard. Version of Oracle DB is 11.2.0.4 Standard One Edition. Oracle database works fine on server. I had no problems/e

  • HT1491 where is the power search button in itunes

    where is the power search button in itunes. I can only find the podcasts I want by going to the website, and then click on "view in itunes". When I try to search it directly in itunes, it doesn't show up.

  • Linked Button - lf_profitCenter, Not Working correctly

    Hello Experts Can anyone explain why the following code, doesn't work? SAPbouiCOM.Item itemLbtnCC; SAPbouiCOM.LinkedButton LbtnCC; itemLbtnCC = this.Form.Items.Add("lnCC", SAPbouiCOM.BoFormItemTypes.it_LINKED_BUTTON); LbtnCC = (SAPbouiCOM.LinkedButto

  • Forms Builder 10g LOV

    I'm a Beginner of Form-Builder. My Questions: 1- I habe read that you can display a LOV at Runtime by pressing a LOV-Button. Does this exist? 2- For the LOV-Property "Automatic Select" you habe to set "Automstic confirm" to YES. How can I do this? Is