Home > OS >  JAVA: Get current time without methods
JAVA: Get current time without methods

Time:05-07

I am trying to do it without methods so that I can better grasp the concept.

I am really close. My hours math seems to be off. What am I not understanding there?

    static void showCurrent(){
        Date today = new Date();
        long milliseconds = today.getTime(); // ex: 1651773923837
        
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;

        long s = seconds % 60;
        long m = minutes % 60;
        long h = hours % 24;

        System.out.printf("Date: %s, Time: %d\n", today.toString(), milliseconds);
        System.out.println(h   ": "   m   ": "   s );

Output:

Date: Fri May 06 10:13:21 EDT 2022, Time: 1651846401839
14: 13: 21

CodePudding user response:

Avoid legacy date-time classes

The toString method on java.util.Date has the unfortunate anti-feature of applying the JVM`s current default time zone while generating the text.

Never use Date. Replaced years ago by the modern java.time classes.

Instant

Use java.time.Instant.

Capture the current the moment.

Instant instant = Instant.now() ;

Generate text in standard ISO 8601 format.

String output = instant.toString() ;

Get a count of milliseconds since the epoch reference of first moment of 1970 as seen with an offset from UTC of zero hours-minutes-seconds, 1970-01-01T00:00Z.

long millis = instant.toEpochMilli() ;

CodePudding user response:

According to Javadoc about Date::getTime:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object

The important part is "GMT" which is different from your timezone : EDT, which is... GMT - 4:00

CodePudding user response:

The LocalDateTime.now() method returns the instance of LocalDateTime class so if you print the instance of LocalDateTime class, it will print the current time and time. To get it the the right format you need to format the current date using DateTimeFormatter class included in JDK 1.8

import java.time.format.DateTimeFormatter;  
import java.time.LocalDateTime;    
public class CurrentDateTime {    
  public static void main(String[] args) {    
   DateTimeFormatter date_wanted = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");  
   LocalDateTime now = LocalDateTime.now();  
   System.out.println(date_wanted.format(now));  
  }    
} 
  • Related