Reputation: 119
My program will take the current system time in HH:MM:SS and convert it into seconds. The reason i convert it into second is because i want to find out the time that was 90 seconds ago.
For example :
Current time : 12:30:30
Time 90 sec ago : 12:29:00
But i can't make it to the correct timestamp. Here are the output from my program :
This is the hour in sec :28800
This is the minute in sec : 1500
This is the second :0
This is the total second after minus 90 sec :30210
The converted time after minus 90 sec :00:01:210
When i issued date +%T
command in my linux terminal, it's show me 08:26:09
.The time displayed in my program not even close to my current system time. I had set the time zone into PDT but also not able to solve the problem. My linux machine is using PDT timezone,i am not sure is it because of the time zone problem. For your reference,please refer to my code stated below
import java.time.LocalDateTime;
import java.text.SimpleDateFormat;
import java.util.*;
class IP
{
public static void main(String [] args)
{
int hour1 = (LocalDateTime.now().getHour())*3600;
int min1 = LocalDateTime.now().getMinute()*60;
int sec1 = LocalDateTime.now().getSecond();
System.out.println("This is the hour in sec :" +hour1);
System.out.println("This is the minute in sec : "+min1);
System.out.println("This is the second :"+sec1);
long Tsec1 = (hour1 + min1 + sec1)-90;
System.out.println("This is the total second after minus 90 sec :"+Tsec1);
TimeZone tz1 = TimeZone.getTimeZone("PDT");
SimpleDateFormat for1 = new SimpleDateFormat("HH:MM:SS");
for1.setTimeZone(tz1);
System.out.println("The converted time after minus 90 sec :" +for1.format(new Date(Tsec1)));
}
}
Upvotes: 1
Views: 57
Reputation: 6969
If you are using Java 8 just use the minusSeconds method in LocalDateTime
If you are using a lower version use the Calendar
Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(Calendar.SECOND, -5);
System.out.println(calendar.getTime());
Don't go around manipulating time manually like this, it will eventually fail at some corner case you haven't thought of.
EDIT:
You can use the DateTimeFormatter
in Java 8 like Dawood pointed out.
Or you can use SimpleDateFormat
in Java 7.
The thing to keep in mind is that SimpleDateFormat is not thread safe, while the newer DateTimeFormatter is.
Upvotes: 1
Reputation: 3881
As you just need the time, you can use LocalTime
of java.time
. Example below:
LocalTime now = LocalTime.now(ZoneId.systemDefault());
System.out.printf("Current Time: %s\n", now); // Current Time: 10:20:55.894
LocalTime ninetySecBefore = now.minusSeconds(90);
System.out.printf("Ninety Seconds earlier : %s\n", ninetySecBefore); // Ninety Seconds earlier : 10:19:25.894
System.out.println(ninetySecBefore.format(DateTimeFormatter.ofPattern("hh:mm:ss"))); //10:19:25
Upvotes: 0