Solved

calculating timestamp operations

Posted on 2013-11-20
8
194 Views
Last Modified: 2013-12-10
hi guys

I have this code

I am trying to get the currentTime at which my program runs and want to get 7 hours prior to that


DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 
Calendar cal = Calendar.getInstance();  
String currentRunningTime = dateFormat.format(cal.getTime()); //current time at which my program runs
String sevenHoursPreviousTime = "";

Open in new window

so if currentRunningTime =  2013-11-19 13:21:55.027
i want to subtract 7 hours from currentRunningTime.

Any idea how i can do that?
Any help would be appreciated.

thanks
0
Comment
Question by:royjayd
  • 4
  • 3
8 Comments
 
LVL 27

Accepted Solution

by:
dpearson earned 142 total points
ID: 39663400
You want something like this:

Calendar cal =       cal.add(Calendar.HOUR_OF_DAY, -7) ;      // 7 hours ago

Doug
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 142 total points
ID: 39663417
Try

	Calendar c = Calendar.getInstance();
	c.add(Calendar.HOUR, -7);
	String sevenEarlier = new java.sql.Timestamp(c.getTime().getTime()).toString();
	System.out.println(sevenEarlier);

Open in new window

0
 
LVL 14

Assisted Solution

by:jb1dev
jb1dev earned 141 total points
ID: 39663852
As Doug suggests, you can use the calendar class.

You can also do it without making use of the Calendar class by calculating the milliseconds yourself.

E.g.
import java.util.*;
import java.text.*;

public class Time {
    
    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String currentRunningTime = dateFormat.format(System.currentTimeMillis());
        String sevenHoursPreviousTime = dateFormat.format(
                    System.currentTimeMillis() - 
                    (1000 * 60 * 60 * 7) );

        System.out.println(currentRunningTime);
        System.out.println(sevenHoursPreviousTime);

    }

}

Open in new window

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 14

Expert Comment

by:jb1dev
ID: 39663859
Also, I would highly recommend against using the java.sql.Timestamp class if you are not working directly with SQL in some kind of persistence layer.
0
 
LVL 14

Expert Comment

by:jb1dev
ID: 39663870
Sorry, it is more accurate to call the System.currentTimeMillis() function only once (otherwise you are off by a few milliseconds)
This is better.

import java.util.*;
import java.text.*;

public class Time {
    
    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long currentTimeMillis = System.currentTimeMillis();
        String currentRunningTime = dateFormat.format(currentTimeMillis);
        String sevenHoursPreviousTime = dateFormat.format(
                    currentTimeMillis - (1000 * 60 * 60 * 7) );

        System.out.println(currentRunningTime);
        System.out.println(sevenHoursPreviousTime);

    }

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39663913
Also, I would highly recommend against using the java.sql.Timestamp class if you are not working directly with SQL in some kind of persistence layer.
Why is that?
0
 
LVL 14

Expert Comment

by:jb1dev
ID: 39663974
Why would you want to use java.sql.* classes outside of the context of JDBC?

This is a great way to introduce bugs when someone has a java.util.Date and they want to compare against a java.sql.Timestamp (which is a subclass and could be passed around as the base class, hiding it's true type from the user.)

From the javadoc:
http://docs.oracle.com/javase/7/docs/api//java/sql/Timestamp.html

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn't an instance of java.sql.Timestamp, because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.

Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39664021
Why would you want to use java.sql.* classes outside of the context of JDBC?
Because it's a smple tool to do a simple job - namely to get a timestamp as a String in the format that royjayd needs. Your observations on type complexity do not seem to be relevant to this case
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JavaFX TableView not displaying correctly 3 55
CSV file parsing thru Java 13 34
How to configure empty element in XML Document parser? 15 36
junit as external jar or library 7 22
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question