0

Hello i'm new to java and i'm trying to figure out how to use modulus to transform the current time in to seconds. this is what i have so far but i don't know where to go from here.

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class firstprogram{

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");


        System.out.println( sdf.format(cal.getTime()) );
    }
mehrdad khosravi
  • 2,228
  • 9
  • 29
  • 34
MGG
  • 11
  • 2

5 Answers5

1

This can be one of many possible ways:

Output This is time in seconds

22525

Code

import java.util.*;

public class HelloWorld {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY) * 3600 + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND));
    }
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • Thank you so much this works great, can you explain your import statement? – MGG Aug 22 '16 at 06:42
  • @MGG as you can see I've used object of `Calendar` class. It is from `java.util.Calendar` package. In order to use it, I've to import this package. You can read more about it from the official documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html – Raman Sahasi Aug 22 '16 at 06:45
  • oh so the pakage "*" contains the calendar? – MGG Aug 22 '16 at 06:49
  • 1
    @MGG the class `Calendar` is part of the package `java.util`. The `*` means import all classes out of the given package. Instead of `import java.util.*;` you could also use `import java.util.Calendar;` – Maximilian Ast Aug 22 '16 at 07:50
  • 1
    as Maximilian said, `*` means `import everything from `java.util` package. You can also use `import java.util.Calendar` – Raman Sahasi Aug 22 '16 at 08:16
1

You can use LocalTime also for this:

long secondsOfDay = LocalTime.now().toSecondOfDay();
System.out.println(secondsOfDay);
Ashwinee K Jha
  • 9,187
  • 2
  • 25
  • 19
0

use only "ss"

public static void main(String[] args) {
    final Calendar cal = Calendar.getInstance();
    final DateFormat sdf = new SimpleDateFormat("ss");
    System.out.println(sdf.format(cal.getTime()));
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Try this:

long seconds = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
Konstantin Labun
  • 3,688
  • 24
  • 24
0

You can also use

long time = System.currentTimeMillis();
long seconds = TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS);
A Joshi
  • 151
  • 1
  • 6