Skip to content

Linux time conversion fail

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 = (*3600;
         int min1 =*60;
         int sec1 =;
         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");        
         System.out.println("The converted time after minus 90 sec :" +for1.format(new Date(Tsec1)));





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

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful